Java Lambda Expressions

By | August 20, 2017

Java lambda expressions are the newest and one of the best additions in Java 8. Java lambda expressions are Java’s one of the first approaches into functional programming.

Java lambda expression is thus a function which can be created without belonging to any class. A lambda expression can be passed around as if it was an object and executed on demand.

Benefits of using Lambda expressions :

  1. To provide the implementation of Functional interface.
  2. Less coding.


(argument-list) -> {body}

i.e. A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body.


Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

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

3) Body: It contains expressions and statements for lambda expression.


Some examples of Java lambda expressions:

Given a number x returns a boolean indicating if it is odd.

x -> x % 2 != 0;

Given a integer c returns a boolean indicating if it is equal to ‘5’

(int c) -> c == 5;

Given two numbers a and b returns another number with their summation

(a, b) -> a + b;

Given two integers m and n returns another integer with the sum of their squares

(int m, int n) -> m * m + n * n;

Given no parameters returns the integer 54

() -> 54;

Given no parameters returns the double 3.1432

() -> { return 3.1432 };

Given a string str prints the string to the main output and returns void.

(String str) -> { System.out.println(str); };

Given no parameters prints “Hello World! This is Lambda” to the main output and returns void.

() -> { System.out.println("Hello World! This is Lambda"); };