Java Lambda Expression

Lambda expression has been introduced in Java since JSE 8. A lambda expression is an anonymous function which doesn’t have a name and doesn’t belong to any class. Also, it can be passed around as if it was an object and executed on demand.

A lambda expression uses the concept of functional interface which is basically an interface with single abstract method (e.g. Runnable, Callable, ActionListener etc.). It is Java’s first step into functional programming like LISP programming language. Lambda expressions implement only abstract function and therefore implement functional interfaces.

Advantages of Lambda Expression :-
  1. It provides implementation of functional interface.
  2. It reduces coding effort.
  3. It can be passed around as if it was an object and executed on demand.

 

Lambda Expression Example

An example will definitely give us a clear concept of lambda expression. The objective is to create a custom interface with a comparator method to compare two objects of Person class by their ages. In the example, the custom interface is named Compare and its comparator method name is compareValues(). We have used here two options— option 1 applies old concept (followed up to Java SE 7), while option 2 employs lambda expression (marked in red color). See the coding example below.

LambdaExpTest.java

interface Compare { // User-defined interface
public Integer compareValues(T o1, T o2); // abstract method
}

class Person {
// instance variables
String name;
Integer age; // not int

// constructor
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

// instance method (getter for name)
public String getName() {
return name;
}

// instance method (getter for age)
public Integer getAge() {
return age;
}

}

public class LambdaExpTest {

public static void main(String[] args) {
Person p1 = new Person("Ram", 40);
Person p2 = new Person("Shyam", 36);

// Option 1: Used up to Java SE 7 with anonymous inner class
Compare byAge = new Compare() {
@Override
public Integer compareValues(Person o1, Person o2) {
// using compareTo(Integer val) method of Integer class
return o1.getAge().compareTo(o2.getAge());
}
};

// Option 2: In Java SE 8 using lambda expression
byAge = (Person o1, Person o2) -> o1.getAge().compareTo(o2.getAge());

int val = byAge.compareValues(p1, p2); //this is mandatory for all options
if(val>0)
System.out.println(p1.name + " is senior to " + p2.name);
else
System.out.println(p2.name + " is senior to " + p1.name);
}
}

Output:

Ram is senior to Shyam

 

 

Explanation of Lambda Expression

Let us discuss the individual parts of the lambda expression used in the previous example:

 

  • Lambda parameters: It denotes the parameter list of the compareValues() method of the user-defined interface Compare for two Person objects.
  • Arrow symbol: The arrow symbol -> denotes the lambda operator that separates the parameter list from the lambda body.
  • Lambda body: Compare two Person objects using their ages. The expression considers the lambda’s return value.

 

 

Lambda Expression Syntax

In a lambda expression, we assign input parameters (if there are any) on the left side of the lambda operator ->, and place the body of statements on the right side of lambda operator. For example, the lambda expression (x, y) -> x * y specifies that lambda expression takes two arguments x and y and returns the multiplication of these arguments.

//Syntax of lambda expression
(Lambda_parameters) -> Lambda_body

NOTE: A lambda expression only has parameter list and body. It doesn’t have any name unlike the methods in Java.

Here, the lambda operator can be:

  • No parameter
  • Single parameter
  • Multiple parameters

The examples for all these scenarios are given below.

 

Lambda Expression Syntax Example

Let us see some coding examples of Lambda expression syntax. We can also mark a functional interface with the annotation named @FunctionalInterface.

I. Lambda Expression Example with No Parameter

LambdaExpTest01.java

@FunctionalInterface
interface Print {
public String print();
}

public class LambdaExpTest01 {

public static void main(String[] args) {
// lambda expression with no parameter
Print p = () -> {
return "Hello, Lambda Expression!";
};
System.out.println("STRING = " + p.print());
}
}

Output:

STRING = Hello, Lambda Expression!

 

II. Lambda Expression Example with Single Parameter

LambdaExpTest02.java

@FunctionalInterface
interface Increment {
public int incrByTen(int a);
}

public class LambdaExpTest02 {

public static void main(String[] args) {
// lambda expression with single parameter
Increment incr = (number) -> number + 10;
System.out.println("Value = " + incr.incrByTen(25));
}
}

Output:

Value = 35
 
III. Lambda Expression Example with Multiple Parameters

LambdaExpTest03.java

@FunctionalInterface
interface Multiplication {
public int multiply(int a, int b);
}

public class LambdaExpTest03 {

public static void main(String[] args) {
// lambda expression with multiple parameters
Multiplication mult = (x, y) -> x * y;
System.out.println("Result = " + mult.multiply(15, 12));
}
}

Output:

Result = 180

 

 

Lambda Expression Example using Multiple Statements

In lambda expression, if there is only one statement, the use of return keyword is optional. However, we must use return keyword when the lambda expression contains multiple statements.

LambdaExpTest04.java

@FunctionalInterface
interface Addition {
public int add(int a, int b);
}

public class LambdaExpTest04 {

public static void main(String[] args) {
// lambda expression with single statement (no return)
Addition a1 = (x, y) -> x + y;
System.out.println("Result1 = " + a1.add(30, 25));

// lambda expression with multiple statements (using return)
Addition a2 = (int x, int y) -> { //even we can pass the type of arguments
int val = x + y;
return val;
};
System.out.println("Result2 = " + a2.add(50, 40));
}
}

Output:

Result1 = 55
Result2 = 90

 

 

Lambda Expression Example using forEach loop

We can iterate through the items of an ArrayList collection using a simple lambda expression together with forEach loop.

LambdaExpTest05.java

import java.util.ArrayList;

public class LambdaExpTest05 {

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Book");
list.add("Pen");
list.add("Pencil");
list.add("Diary");
list.add("Notebook");

System.out.println("List items are:~ ");
System.out.println("===============");
list.forEach((item) -> System.out.println(item));
}
}

Output:

List items are:~ 
===============
Book
Pen
Pencil
Diary
Notebook