Home core java Java Lambda Expression with examples

Java Lambda Expression with examples

1. what is Java Lambda (λ) Expression ?

A Java lambda expression is a function which can be created without belonging to any class. Lambda expression is an anonymous function that allows you to pass methods as arguments. Lambda expressions enable you to do functionality as method argument, or code as data. The Main Objective Lambda (λ) Expression is to bring benefits of functional programming into java.

2. Java Lambda Expression Syntax :

(argument-list) -> {body}

Argument-list : List of lambda method arguments, It can be empty or non-empty as well.

Arrow-token: It is used to link arguments-list and body of expression.

Body: It contains expressions and statements for lambda expression.

Example :

(int a, int b) -> {System.out.println(a+b);};

2.1. The type of the parameter can be decided by compiler automatically based on the context, so the parameter type is optional, can omit the argument type.

Example :

(a, b) -> {System.out.println(a+b);};

2.2. If only one parameter is available and if the compiler can expect the type then we can remove the type and parenthesis also.

Example :

num -> {System.out.println(num % 2);};

2.3. Method body of lambda expression also can contain multiple statements. If more than one statements present then we have to enclose inside within curly braces. If one statement present then curly braces are optional.

Example 1:

      num -> {
               System.out.println(num % 2);
               System.out.println(num > 10);
             };

Example 2:

num -> System.out.println(num % 2);

2.4. Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required. A functional interface is an interface with only one abstract method. Also we can mark interface with @FunctionalInterface annotation to enforce an interface have only one method

3. Java lambda expression examples

3.1. Lambda Example 1

@FunctionalInterface
interface MyFunctionalInterface {
    
    void add(int a, int b);
}
public class LambdaTest1 {
	public static void main(String[] args) {

		// Lambda Expreassion 1
		MyFunctionalInterface f = (int a, int b) -> {
			System.out.println(a * b);
		};
		f.add(4, 5);// 20

		// Lambda Expreassion 2
		MyFunctionalInterface f2 = (a, b) -> System.out.println(a + b);
		f2.add(4, 5);// 9
	}
}

Output :

20
9

3.2. Lambda Example 2

Runnable Interface is java built-in Functional interface. Here defining lambda expression that refers to Runnable interface run() and then passing Runnable reference to the Thread class to start thread.

public class LambdaTest1 {
	
	public static void main(String[] args) {

        new Thread(() -> {
            for(int i=0; i < 5; i++)
               System.out.println("Child Thread "+i);
        }).start();;
        
        for(int i=0; i < 5; i++) {
            System.out.println("Main Thread "+i);
        }
    }
}

Output :

Main Thread 0
Main Thread 1
Main Thread 2
Main Thread 3
Main Thread 4
Child Thread 0
Child Thread 1
Child Thread 2
Child Thread 3
Child Thread 4

3.3. Lambda Example 3

Following example shows you defining lambda expression for Predicate built-in java functional interface whose functional method is test it takes single argument and return boolean value.

public class LambdaTest3 {
	
	public static void main(String[] args) {
        // Defining Lambda Expression for Predicate Functional interface
        Predicate<Integer> p = number -> (number % 2 == 0);
 
        System.out.println(p.test(10));//true
        System.out.println(p.test(11));//false
    }
}

Output :

true
false

3.4. Lambda example 4

Following example show you iterate list using forEach , the input argument of forEach is Consumer interface, it’s also a built-in functional interface whose functional method takes single argument as input and return nothing.

public class LambdaTest4 {
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
        list.add("Peter");
        list.add("Gerhard");
        list.add("Philip");
        list.add("John");
        
        list.forEach(value -> System.out.println(value));  
    }
}

Output :

Peter
Gerhard
Philip
John

References

  1. Java documentation
  2. Runnable document
  3. Functions document

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

Stay in Touch

Categories