x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Lambda Expressions in Java

    A Lambda expression (introduced in Java 8) is a concise way of writing an instance of a class that implements a functional interface. An interface with single abstract method is called functional interface. For example Runnable interface. It has just one method run(). To implement a Lambda Expression, use an → symbol with paremeters on the left and a method body on the right.

    1) Following Java Lambda Expressions example shows how to implement a simple interface without actually creating the concrete class.

    // A sample functional interface (An interface with single abstract method)
    public interface Calculator {  
        int add(int a,int b);  
    }  			
    

    Without Lambda Expressions

    public class LambdaExpressionsTest {
        public static void main(String[] args) {
            Calculator calculator = new Calculator() { 
                public int add(int a,int b) {
                    return a+b;
                }
            };
            System.out.println(calculator.add(1,2)); // prints 3  
           
       }
    }
    
    

    With Lambda Expressions in Java

    	
    public class LambdaExpressionsTest {
        public static void main(String[] args) {
            Calculator calculator = (a,b)->(a+b);
            System.out.println(calculator.add(1,2)); // prints 3  
    			
            calculator =(int a,int b)->{return (a+b);   
            };
            System.out.println(calculator.add(20,30));  // prints 50
            
            calculator = (a,b)-> {return (a+b);};
            System.out.println(calculator.add(20,40));  // prints 60
            
            // following will not compile
            calculator = (a,b)-> return (a+b);
       }
    }
    	

    2) Following Java Lambda Expressions example shows how to pass Lambda expressions as method argument.

    // A sample functional interface (An interface with single abstract method)   
    public interface EmployeeQuery {
        public boolean queryEmployee(Employee employee);
    }    
    
    import java.util.ArrayList;
    import java.util.List;
    	
    class Employee {  
    
        private int age;
        private String name;
    		
        public Employee(String name, int age) {
            this.name = name;
            this.age = age;
        }
    		
        // getter, setter removed    
    	
    }  			
    
    public class Test {
        public static void main(String[] args) {
            Employee e1 = new Employee("Mark", 30); 
            Employee e2 = new Employee("Harry", 40);
            Employee e3 = new Employee("Johnny", 50);
            List<Employee> employees = new ArrayList<>();
            employees.add(e1);
            employees.add(e2);
            employees.add(e3);
                
            for (Employee employee : employees) {
               printEmployeeName(employee, e -> e.getAge() > 30);
            }
        }
    		
        private static void printEmployeeName(Employee employee, EmployeeQuery employeeQuery) {
            if (employeeQuery.queryEmployee(employee)) {
                System.out.println(employee.getName());
            }
        }
    		
    }
    	

    Output :

    Harry
    Johnny		

    3) Following Java Lambda Expressions example shows how to use Lambda Expressions using for loop for iterating a list

    import java.util.ArrayList;
    import java.util.List;
    	
    public class TestClass { 
        public static void main(String[] args) {
          
            List<String> fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.stream().forEach((string) -> {System.out.println(string);
            }  );
        }
    }
    	

    Output :

    Apple
    Banana		

    4) Sorting by Using Comparator Interface

    import java.util.ArrayList;
    import java.util.List;
    	
    class Celebrity  {
    
        private String name;
        private int rank;
        private int networth;
    
        Celebrity (String name, int rank, int networth) {
            this.name = name;
            this.rank = rank;
            this.networth = networth;
        }
            
        // getter setter removed
    	
        @Override
        public String toString() {
            return "Celebrity [name=" + name + ", rank=" + rank + ", networth="+ networth + "]";
        }
    		
    }
    						
    public class MyClass {
        public static void main(String[] args) {
            List<Celebrity> celebrities = new ArrayList<Celebrity>();
            Celebrity celebrity1 = new Celebrity("Harry", 1, 100000);
            Celebrity celebrity2 = new Celebrity("IronMan", 3, 2000000);
            Celebrity celebrity3 = new Celebrity("Batman", 2, 50000);
                
            celebrities.add(celebrity1);
            celebrities.add(celebrity2);
            celebrities.add(celebrity3);
    		
            celebrities.sort( (Celebrity c1, Celebrity c2)-> c1.getNetworth()- c2.getNetworth() );		
            celebrities.forEach( (celebrity)->System.out.println(celebrity) );
           
        }
    }	

    Output :

    Celebrity [name=Batman, rank=2, networth=50000]
    Celebrity [name=Harry, rank=1, networth=100000]
    Celebrity [name=IronMan, rank=3, networth=2000000]
    		


    References :

    Oracle Docs Lambda Expressions

    Oracle Docs Functional Interface