dsa

Java Lambda Expression

In this tutorial, we will learn about the Java Lambda Expression with the help of an example.

Lambda expressions basically express instances of functional interfaces (An interface with single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces

Example


// Java program to demonstrate lambda expressions 
// to implement a user defined functional interface. 

// A sample functional interface (An interface with single abstract method 
interface FuncInterface 
{ 
	// An abstract function 
	void abstractFun(int x); 

	// A non-abstract (or default) function 
	default void normalFun() 
	{ 
	System.out.println("Hello"); 
	} 
} 

class Test 
{ 
	public static void main(String args[]) 
	{ 
		// lambda expression to implement above 
		// functional interface. This interface 
		// by default implements abstractFun() 
		FuncInterface fobj = (int x)->System.out.println(2*x); 

		// This calls above lambda expression and prints 10. 
		fobj.abstractFun(5); 
	} 
} 

Output:

10

Syntax:

lambda operator -> body

Example:



// A Java program to demonstrate simple lambda expressions 
import java.util.ArrayList; 
class Test 
{ 
	public static void main(String args[]) 
	{ 
		// Creating an ArrayList with elements 
		// {1, 2, 3, 4} 
		ArrayList arrL = new ArrayList(); 
		arrL.add(1); 
		arrL.add(2); 
		arrL.add(3); 
		arrL.add(4); 

		// Using lambda expression to print all elements 
		// of arrL 
		arrL.forEach(n -> System.out.println(n)); 

		// Using lambda expression to print even elements 
		// of arrL 
		arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); }); 
	} 
} 


Output:

1
2
3
4
2
4