Lambda Expressions in Java SE 8

Introduction

In this article we will learn how to work with Lambda Expressions. As we know a Lambda Expression is one of the most awaited and hyped functions of Java SE 8. People have differing points of views of Lambda Expressions. Before we start, let's understand what Lambda Expressions are.

Lambda Expression

Simply a Lambda Expression (a new feature in Java SE 8) is a method without declaration like access modifiers, name, return value and declaration. It allows us to treat code as data and functionality as method arguments. In short, it is a block of code with parameters (arguments) that is useful when a method is being used only once during its life cycle. It allows us to write a block of code at the same place where we want to use it. It replaces anonymous classes and allows us to write code in a functional style. It also improves Collection libraries. Some people say that Lambda Expressions are just like Anonymous Classes, but the following are the differences.

Differences between Lambda Expression and Anonymous Class

Lambda Expression Anonymous Class
In Lambda Expression "this" keyword resolves to the enclosing class In Anonymous Class "this" keyword resolves to the anonymous class
When compiling a Lambda Expression is converted into a private method of the class When compiling, it generates "class_name$some_number.class file"

Some of the examples are given below that helps us to understand Lambda Expression.

For example, If we write the code of the thread in Java 7 it looks like:

  1. import java.lang.*;    
  2. public class old_Thread extends Thread    
  3. {    
  4.     public void run()    
  5.     {    
  6.        System.out.println("Thread running in Java 7");    
  7.     }    
  8.     public static void main(String args[])    
  9.     {    
  10.         old_Thread obj = new old_Thread();    
  11.         obj.start();    
  12.     }    
  13. }  
Output
 
 
 
In Java 8: Now, the same things in Java 8 with the use of Lambda Expression, it looks like:
  1. import java.lang.*;  
  2. public class lambThread extends Thread  
  3. {  
  4.     public static void main(String args[])  
  5.     {  
  6.         new Thread( () -> System.out.println("Thread running with Lambda expression ")).start();  
  7.     }  
  8. }  
Output
 
 

Example: Let's use another example of runnable code in Java 7.

  1. import java.lang.*;  
  2. public class old_Run extends Thread implements Runnable  
  3.  {  
  4.     public void run()  
  5.     {  
  6.        System.out.println("Thread running in Java 7 with Interface");  
  7.     }  
  8.     public static void main(String args[])  
  9.     {  
  10.         old_Run obj = new old_Run();  
  11.         obj.start();  
  12.     }  
  13. }  

 Output

  

In Java 8: Now, the same things in Java 8 using a Lambda Expression, it looks like:
  1. public class lambRun extends Thread implements Runnable  
  2. {  
  3.     public static void main(String args[])  
  4.     {  
  5.         Runnable r = () -> System.out.println("Thread Run with Lambda Expression using Runnable Interface");  
  6.         r.run();  
  7.       
  8.     }  
  9. }  
Output
 

 
Example: In Java 8, we can use a double colon (: :) for printing as in the following:
  1. import java.util.*;  
  2. public class lamb_colon  
  3. {  
  4.     public static void main(String args[])  
  5.     {  
  6.         String[] atp = {"M S Dhoni""Sachin Tendulkar""Virat Kholi""Suresh Raina""Zahir Khan""Irfan Pathan""Harbajan Singh""Asheesh Nehra"};  
  7.         List<String> players =  Arrays.asList(atp);  
  8.         System.out.println("");  
  9.         // Using double colon operator in Java 8  
  10.         players.forEach(System.out::println);  
  11.           
  12.     }  
  13. }  
 Output
 
 

Example: Let's use an example of looping, the code in Java 7.

  1. import java.util.*;  
  2. public class loop  
  3. {  
  4.     public static void main(String args[])  
  5.     {  
  6.         String[] atp = {"M S Dhoni""Sachin Tendulkar""Virat Kholi""Suresh Raina""Zahir Khan""Irfan Pathan""Harbajan Singh""Asheesh Nehra"};  
  7.         List<String> players =  Arrays.asList(atp);  
  8.         System.out.println("");  
  9.         // old looping  
  10.         System.out.println("Print with Java 7 Looping");  
  11.         for (String player : players)  
  12.         {     
  13.             System.out.println(player);  
  14.         }  
  15.     }  
  16. }  
Output
 
 

In Java 8: Now, the same thing in Java 8 using a Lambda Expression, it looks like:

  1. import java.util.*;  
  2. public class lamb_func  
  3. {  
  4.     public static void main(String args[])  
  5.     {  
  6.         String[] atp = {"M S Dhoni""Sachin Tendulkar""Virat Kholi""Suresh Raina""Zahir Khan""Irfan Pathan""Harbajan Singh""Asheesh Nehra"};  
  7.         List<String> players =  Arrays.asList(atp);  
  8.         System.out.println("");  
  9.         // Using lambda expression and functional operations  
  10.         players.forEach((p) -> System.out.println(p + "; "));  
  11.           
  12.     }  
  13. }  
Output
 
 

Example: Let's use an example of sorting, Code in Java 7. 

  1. import java.util.*;  
  2. import java.util.Arrays;  
  3. public class sorting  
  4. {  
  5.     public static void main(String args[])  
  6.     {  
  7.         String[] players = {"M S Dhoni""Sachin Tendulkar""Virat Kholi""Suresh Raina""Zahir Khan""Irfan Pathan""Harbajan Singh""Asheesh Nehra"};  
  8.         Arrays.sort(players);  
  9.         System.out.println("");  
  10.         System.out.println("Print with Java 7 sorting");  
  11.         for(String player : players)  
  12.             {  
  13.                 System.out.println(player);  
  14.             }  
  15.     }  
  16. }  

Output

 

In Java 8: Now, the same thing in Java 8 using a Lambda Expression, it looks like:

  1. import java.util.*;  
  2. import java.util.Arrays;  
  3. public class lamb_sort  
  4. {  
  5.     public static void main(String args[])  
  6.     {  
  7.         String[] players = {"M S Dhoni""Sachin Tendulkar""Virat Kholi""Suresh Raina""Zahir Khan""Irfan Pathan""Harbajan Singh""Asheesh Nehra"};  
  8.         List<String> player =  Arrays.asList(players);  
  9.         System.out.println("");  
  10.         // Sort players by name using lambda expression  
  11.         Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));  
  12.         Arrays.sort(players, sortByName);  
  13.         // or this  
  14.         Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));  
  15.         player.forEach(System.out::println);  
  16.     }  
  17. }  
Output
 
 

Example: This example shows the use of the Filter method in Java 8 using a Lambda Expression.

  1. import java.io.*;    
  2. import java.util.*;    
  3. import java.util.function.Predicate;    
  4. public class lamb_filter     
  5. {    
  6.     public static void main(String [] a)      
  7.     {    
  8.         List<Integer> list = Arrays.asList(123456);    
  9.         System.out.println("List Contain");    
  10.         evaluate(list, (n)->true);  
  11.         System.out.println("Empty List");    
  12.         System.out.println("");    
  13.         evaluate(list, (n)->false);   
  14.         System.out.println("Even Numbers are:");    
  15.         evaluate(list, (n)-> n%2 == 0 );    
  16.         System.out.println("Odd Numbers are:");    
  17.         evaluate(list, (n)-> n%2 == 1 );    
  18.         System.out.println("Numbers smaller than 3 are:");    
  19.         evaluate(list, (n)-> n < 3 );    
  20.         System.out.println("Numbers greater than 3 are:");    
  21.         evaluate(list, (n)-> n > 3 );    
  22.      }    
  23.      public static void evaluate(List<Integer> list, Predicate<Integer> predicate)  
  24.      {    
  25.         for(Integer n: list)      
  26.         {    
  27.             if(predicate.test(n))     
  28.             {    
  29.                 System.out.println(n + " ");    
  30.             }    
  31.         }    
  32.     }    
  33. }    

Output

 
 
Summary

The summary of this article is that we have implemented Lambda Expressions in various ways and learned how to work with them. It is also helpful to write clean code and it will take Java to the next level.

Up Next
    Ebook Download
    View all
    Learn
    View all