Learnitweb

How to write and use a lambda expression in Java 8?

Lambda expression is an anonymous function. A lambda expression

  • does not have a name
  • does not have modifier
  • does not have return type

We’ll learn to convert normal method in to a lambda expression with the help of a simple “Hello World” example.

public void foo() {
	System.out.println("Hello World");
}

Since a lambda expression does not have a name, modifier and return type, it’s equivalent lambda expression is:

() -> {System.out.println("Hello World");}

If lambda expression has only one executable statement, then curly braces {} are optional. So we can write above lambda expression as:

() -> System.out.println("Hello World");

Let use see another example.

public int getSum(int firstNumber, int secondNumber){
	return firstNumber + secondNumber;
}

The lambda expression for above function is:

(int firstNumber, int secondNumber) -> { return firstNumber + secondNumber;}

In Java 8, type inference has been improved. Based on the context (how lambda expression is used), compiler can identify the types. Using type inference, we can remove type of input parameters. We can write the above lambda expression as

(firstNumber, secondNumber) -> { return firstNumber + secondNumber;}

Multi-line lambda expression

A lambda expression may also have multiple executable statements. For example:

() -> {	
	System.out.println("Hello");
	System.out.println("World");
}

How to use a Lambda expression

A Java functional interface can be implemented by a Java lambda expression. In the following example, TestFunctionalInterface is a functional interface. Lambda expression is assigned to the func which is of type TestFunctionalInterface. Since TestFunctionalInterface has only one function, so identifying which method to execute for lambda expression should not be an issue.

import java.lang.FunctionalInterface;

@FunctionalInterface
interface TestFunctionalInterface {
	public void print();
}

public class Test{
	public static void main(String args[]) {
		TestFunctionalInterface func = () -> System.out.println("Hello world");
		func.print();
	}
}