Lambda Expression

It is a shorter way of writing an implementation of a method which we can execute later at some point.

Syntax :

  1. (arg1,arg2,arg3,…)  -> {body of implementing method};
(arg1,arg2,arg3,…)  -> {body of implementing method};


Example 1 :

  1. (int x, int y,int z) -> {  return x + y + z; };
  2.  
(int x, int y,int z) -> {  return x + y + z; };
 


Example 2 :

  1. () -> System.out.println("no arg method");
  2.  
() -> System.out.println("no arg method");
 


Example 3 :

  1. (String s) -> { System.out.println(s); };
  2.  
(String s) -> { System.out.println(s); };
 


Example 4 :

  1. () -> 10
  2.  
() -> 10
 


Example 5 :

  1. () -> { return 3.14 };
() -> { return 3.14 };

Note :
Lambda can be used only for functional interfaces Even if there is an abstract class with one and only one abstract method also Lambda will not work.


Consider an abstract class as below

  1. package com.kb.Lambda;
  2.  
  3. public abstract class AbstractClass {
  4. abstract void show();
  5. }
package com.kb.Lambda;

public abstract class AbstractClass {
abstract void show();
}


Create an implementor

  1. package com.kb.Lambda;
  2.  
  3. public class AbstractClassImplementor {
  4.  
  5.     public static void main(String[] args) {
  6.         AbstractClass abstractClass = new AbstractClass() {
  7.            
  8.             @Override
  9.             void show() {
  10.                 System.out.println("show called");
  11.                
  12.             }
  13.         };
  14.  
  15. //New way using lambda
  16. AbstractClass abstractClass1 = () -> System.out.println("show called new way");
  17.  
  18.     }
  19.    
  20. }
package com.kb.Lambda;

public class AbstractClassImplementor {

	public static void main(String[] args) {
		AbstractClass abstractClass = new AbstractClass() {
			
			@Override
			void show() {
				System.out.println("show called");
				
			}
		};

//New way using lambda
AbstractClass abstractClass1 = () -> System.out.println("show called new way");

	}
	
}


No doubt this new way will give the compile time error.

So lambda expression can not be used with abstract class even if it is containing single abstarct method.

So it must be used only in case of functional interface.

Key points on Lambda expression are


1) A lambda expression can have zero, one or more parameters which is decided as per the method signature in functional interface.

2) The type of the parameters can be explicitly declared or it can be inferred from the context.
Example : (int a,int b) is same as just (a,b)

3) Empty parentheses should be used to represent an empty set of parameters.
Example : ( ) -> 1

4) If method in functional interface has single parameter, and it’s type is inferred, it is not mandatory to use parentheses.
Example : a -> return a+a;

5) If body of lambda expression has single statement, curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

6) When there is more than one statement in body than these must be enclosed in curly brackets and the return type of the anonymous function is the same as the type of the value returned within the block, or void if nothing is returned.

Below are few examples on how to use lambda expression

Using lambda expression

  1. package com.kb.Lambda;
  2.  
  3. public class LambdaEx1 {
  4.     public static void main(String[] args) {
  5.         Runnable r = new Runnable() {
  6.            
  7.             @Override
  8.             public void run() {
  9.                 System.out.println("old way of calling run method");
  10.                
  11.             }
  12.         };
  13.        
  14.         r.run();
  15.         Runnable newR = () -> System.out.println("new way of calling run method using Lambda");
  16.         newR.run();
  17.     }
  18.  
  19. }
package com.kb.Lambda;

public class LambdaEx1 {
	public static void main(String[] args) {
		Runnable r = new Runnable() {
			
			@Override
			public void run() {
				System.out.println("old way of calling run method");
				
			}
		};
		
		r.run();
		Runnable newR = () -> System.out.println("new way of calling run method using Lambda");
		newR.run();
	}

}
  1. new Thread(
  2.     () -> System.out.println("run method")
  3. ).start();
new Thread(
    () -> System.out.println("run method")
).start();


So in above code, compiler automatically detects that lambda expression can be casted to Runnable interface from Thread class’s constructor signature

  1. public Thread(Runnable r) {
  2. }
public Thread(Runnable r) { 
}


Functional interface with lambda on method call

  1. package com.kb.Lambda;
  2.  
  3. @FunctionalInterface
  4. interface FunctionalInterfaceExample1{
  5.     void show();
  6. }
  7.  
  8. public class FunctionalInterfaceAndLambda {
  9.    
  10.     static void executeFunctionalInterface(FunctionalInterfaceExample1 example1){
  11.         example1.show();
  12.     }
  13.  
  14.    
  15.     public static void main(String[] args) {
  16.        
  17.         //old way1
  18.         executeFunctionalInterface(new FunctionalInterfaceExample1() {
  19.            
  20.             @Override
  21.             public void show() {
  22.                 System.out.println("old way of defining anonymous inner class");
  23.                
  24.             }
  25.         });
  26.        
  27.            // old way2
  28.         FunctionalInterfaceExample1 ex1 = new FunctionalInterfaceExample1() {
  29.            
  30.             @Override
  31.             public void show() {
  32.                 System.out.println("still old way of defining anonymous inner class");
  33.                
  34.             }
  35.         };
  36.        
  37.         executeFunctionalInterface(ex1);
  38.        
  39.        
  40.         //new way using lambda
  41.        
  42.         executeFunctionalInterface(() -> {System.out.println("new way of defining anonymous inner class using lambda");});
  43.        
  44.     }
  45.  
  46. }
package com.kb.Lambda;

@FunctionalInterface
interface FunctionalInterfaceExample1{
	void show();
}

public class FunctionalInterfaceAndLambda {
	
	static void executeFunctionalInterface(FunctionalInterfaceExample1 example1){
		example1.show();
	}

	
	public static void main(String[] args) {
		
		//old way1
		executeFunctionalInterface(new FunctionalInterfaceExample1() {
			
			@Override
			public void show() {
				System.out.println("old way of defining anonymous inner class");
				
			}
		});
		
           // old way2
		FunctionalInterfaceExample1 ex1 = new FunctionalInterfaceExample1() {
			
			@Override
			public void show() {
				System.out.println("still old way of defining anonymous inner class");
				
			}
		};
		
		executeFunctionalInterface(ex1);
		
		
		//new way using lambda
		
		executeFunctionalInterface(() -> {System.out.println("new way of defining anonymous inner class using lambda");});
		
	}

}



Collection iteration with lambda expression


forEach method is added to List interface in Java8 and it can be used as below with lambda.

Create IteratingList.java

  1. package com.kb.Lambda;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.function.Consumer;
  6.  
  7. public class IteratingList {
  8.  
  9.     public static void main(String[] args) {
  10.         List<Integer> list = new ArrayList<Integer>();
  11.         list.add(10);
  12.         list.add(20);
  13.        
  14.         //old way of iterating
  15.         for (Integer element : list) {
  16.             System.out.println(element);
  17.         }
  18.  
  19.         System.out.println("-----------------");
  20.  
  21.         //new way using lambda
  22.         list.forEach(element -> {System.out.println(element);});
  23.  
  24.     }
  25.  
  26. }
package com.kb.Lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class IteratingList {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(10);
		list.add(20);
		
		//old way of iterating
		for (Integer element : list) {
			System.out.println(element);
		}

		System.out.println("-----------------");

		//new way using lambda
		list.forEach(element -> {System.out.println(element);});

	}

}



Arithmetic Operation with lambda expression


Create Calculator.java

  1. package com.kb.Lambda;
  2.  
  3. public class Calculator {
  4.      
  5.     interface IntegerMath {
  6.         int operation(int a, int b);  
  7.     }
  8.  
  9.     public int operateBinary(int a, int b, IntegerMath operation) {
  10.         return operation.operation(a, b);
  11.     }
  12.  
  13.     public static void main(String... args) {
  14.    
  15.         Calculator myApp = new Calculator();
  16.         IntegerMath addition = (a, b) -> a + b;
  17.         IntegerMath subtraction = (a, b) -> a - b;
  18.         System.out.println("40 + 2 = " +
  19.             myApp.operateBinary(40, 2, addition));
  20.         System.out.println("20 - 10 = " +
  21.             myApp.operateBinary(20, 10, subtraction));    
  22.     }
  23. }
package com.kb.Lambda;

public class Calculator {
	  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath operation) {
        return operation.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}



Comparator with lambda expression


Create a class person

  1. package com.kb.Lambda;
  2.  
  3. public class Person {
  4.    
  5.     String name;
  6.     String designation;
  7.     int age;
  8.    
  9.     public String getName() {
  10.         return name;
  11.     }
  12.     public void setName(String name) {
  13.         this.name = name;
  14.     }
  15.     public String getDesignation() {
  16.         return designation;
  17.     }
  18.     public void setDesignation(String designation) {
  19.         this.designation = designation;
  20.     }
  21.     public int getAge() {
  22.         return age;
  23.     }
  24.     public void setAge(int age) {
  25.         this.age = age;
  26.     }
  27.    
  28.     @Override
  29.     public String toString() {
  30.         return "name is "+name+" age is "+age+" designation is "+designation;
  31.     }
  32.  
  33. }
package com.kb.Lambda;

public class Person {
	
	String name;
	String designation;
	int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name is "+name+" age is "+age+" designation is "+designation;
	}

}


Create a client class which uses person

  1. package com.kb.Lambda;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7.  
  8. public class PersonUser {
  9.  
  10.     public static void main(String[] args) {
  11.         Person p1 = new Person();
  12.         p1.setName("kb");
  13.         p1.setDesignation("se");
  14.         p1.setAge(26);
  15.        
  16.         Person p2 = new Person();
  17.         p2.setName("hani");
  18.         p2.setDesignation("se");
  19.         p2.setAge(28);
  20.        
  21.         List<Person> people = new ArrayList<Person>();
  22.         people.add(p1);
  23.         people.add(p2);
  24.         System.out.println("people before sorting");
  25.         System.out.println(people);
  26.         //Collections.sort(people,new PersonComparator());
  27.         Collections.sort(people,new Comparator<Person>() {
  28.             @Override
  29.             public int compare(Person p1, Person p2) {
  30.                 return p1.getName().compareTo(p2.getName()) ;
  31.             }
  32.            
  33.         });
  34.         System.out.println("people after sorting");
  35.         System.out.println(people);
  36.     }
  37. }
package com.kb.Lambda;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PersonUser {

	public static void main(String[] args) {
		Person p1 = new Person();
		p1.setName("kb");
		p1.setDesignation("se");
		p1.setAge(26);
		
		Person p2 = new Person();
		p2.setName("hani");
		p2.setDesignation("se");
		p2.setAge(28);
		
		List<Person> people = new ArrayList<Person>();
		people.add(p1);
		people.add(p2);
		System.out.println("people before sorting");
		System.out.println(people);
		//Collections.sort(people,new PersonComparator());
		Collections.sort(people,new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				return p1.getName().compareTo(p2.getName()) ;
			}
			
		});
		System.out.println("people after sorting");
		System.out.println(people);
	}
}

In the above code Collections.sort( ) method takes comparator type as a parameter and provides implementation to the compareTo() method

Now above Collections.sort( ) method can be replaced using lambda expression as below

  1. Collections.sort(people, (a,b) ->{ return a.getName().compareTo(b.getName());});
Collections.sort(people, (a,b) ->{ return a.getName().compareTo(b.getName());});

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on