Java 8 Lambda Expression with examples

Java 8 Lambda is one of the most awaited features the java community was waiting for. Inclusion of lambda to th is a first step to introduce functional programming in hard core OOPs framework.

What is Lambda

A lambda expression is a block of code that you can pass around so it can be executed later, just once or multiple times. It is a block of code with or without parameters.

How to use lambda?

The main intention of using lambda is to pass a block of code. The code block can be used of immediate execution or can be later too. But Java is object oriented programming and until now creation of any block had to be done by wrapping around the class and creating an object. Lets look at some of the regular java examples:

public class ThreadClass implements Runnable {
  public void run() {
    System.out.println("I am running in a thread");
//create a new thread
ThreadClass tc = new ThreadClass();
new Thread(tc).start();

Consider sorting with a comparator. If we need to write a custom comparator for sorting String by its length then create a new class and implement Comparator interface:

class LengthComparator implements Comparator<String> {
     public int compare(String first, String second) {
        return, second.length());
Arrays.sort(strings, new LengthComparator());

Syntax in Lambda for above expression

The code for creating a thread using lambda

//the Runnable interace method 
Runnable r = () -> { System.out.println("I am running in a thread"); }

Similarily for having a comparator, the code is reduced as follows:

Arrays.sort(someList, (first, second) -> {, second.length());})

It can be seen that lambda makes the code more terse and awfully simpler to read.

Functional Interfaces

As we discussed, there are many existing interfaces in Java that encapsulate blocks of code, such as Runnable or Comparator. Lambdas are backwards compatible with these interfaces.

You can supply a lambda expression whenever an object of an interface with a single abstract method is expected. Such an interface is called a functional interface.

Arrays.sort(someList, (first, second) -> {, second.length());}

In the above example, Arrays.sort method receives a block of code (lambda), as a second argument which is wrapped around an object of some class which implements Comparator<String> interface. The block is executed when compare method is invoked

Method References

Sometimes, there is already a method that carries out exactly the action that you'd like to pass on to some other code. For example, you want to pass the String method equalsIgnoreCase to Arrays.sort method:

//before java 8
Arrays.sorts(string, String.compareToIgnoreCase());
//java 8 lambda style
Arrays.sort(strings, String::compareToIgnoreCase)

Constructor References

This is very similar to method references, except the name of the method is new.

//before java 8
new Person();
new ArrayList()
//java 8 lambda style

Subscribe to get latest updates.