Lambda Expressions in Java 8

Java SE 8 introduces a new and important feature known as Lambda expressions, this feature enable you to treat functionality as method argument (or) code as data. Before going into Lambda expressions lets have few code examples.

Anonymous Inner Class

This allows to implement classes that may occur only one in an application. Let us assume in a Swing  application a number of event handlers are required for keyboard and mouse events. Rather than writing a separate event-handling class for each event, you may write like this.

 

By creating the class in place, where it is needed, the code is a little easier to read.

The code that defines ActionListener Interface, looks like this.

package java.awt.event;
import java.util.EventListener;
public interface ActionListener extends EventListener {
public void actionPerformed(ActionEvent e);

}

The ActionListener is an interface with only one method. With Java SE 8, an interface that follows this pattern is known as a “functional interface”.

Let’s have a look at Lambda expression, which is used to rewrite the above code in much simpler fashion.

A lambda expression is composed of three parts.

Argument List

Arrow Token

Body

(int x, int y)

->

x + y

 

The body can be either a single expression or a statement block. In the expression form, the body is simply evaluated and returned. In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method.

With the basics of syntax covered, let’s look at some examples.

Example 1: Let’s rewrite the code of ActionListener Interface example.

 

   

By passing Lambda expression as argument to ActionListener, the code is a simple to read.

Example 2: Sorting a list of Strings in prior versions of java.

 

The static utility method Collections.sort accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method.

Output:

Before Sort : [ram, raju, gold, silver]

After Sort : [gold, raju, ram, silver]

Instead of creating anonymous objects, Java 8 comes with a much shorter syntax using lambda expressions: Let’s look at below example:

Output:

Before Sort : [ram, raju, gold, silver]

After Sort : [gold, raju, ram, silver]

 

Lambda expressions  is used in a number of contexts, as follows:

  • Variable declarations
  • Assignments
  • Return statements
  • Array initializers
  • Method or constructor arguments
  • Lambda expression bodies
  • Conditional expressions ?:
  • Cast expressions