Lambda Expression Tutorial

Lambda expressions are one of the new additions to Java 8.  It is also one of the most talked about and exiting features of Java 8.  We will cover what exactly are Lambda expressions and some examples in this article.

What are Lambda Expressions?

Lambda expressions are a way use a expression to represent function calls which are usually on anonymous classes.  Usually anonymous inner classes have just one method and extend some interface.  The entire purpose of writing anonymous inner classes is to implement a single method.  Lambda expressions can help us reduce the code written around anonymous inner classes by reducing to to a single statement.

Here is a simple example of Lambda expression –

( i ) -> (System.out.println(i));

Let us see an example.

In the following class following is happening –

Let us assume that you want to sort a array list of Integers using a anonymous class which implements Comparator interface.  Here are the steps –

  1. Initialize a ArrayList of integers. (Line 10)
  2. We want to sort the numbers in the list so we take help of anonymous class which implements Comparator interface (Line 11).  There is only one method inside it called compare which contains the logic for comparison.  We call the compare method in the instance of the anonymous class (Line 12).  This method compares the values in the list and returns a sorted list.
  3. Once the list is sorted we print the list (Line 17 – 20).
package com.freetipscentral.domain;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LambdaExample1 {
  public static void main(String args[]) {
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,20);
    Collections.sort(numbers, new Comparator<Integer>(){
      public int compare(Integer i1, Integer i2){
        return i1.compareTo(i2);
      }
    });
    
    for(Integer i : numbers) {
      System.out.println(i);
    }
  }
}

Here is the output of above code –

1
2
3
4
5
6
7
8
9
20

Lambda Expression For the Above Code

The above code can also be written using Lambda expressions.  Once we translate the Anonymous class to Lambda expression here is how the class looks like –

package com.freetipscentral.domain;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LambdaExample1 {
  public static void main(String args[]) {
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,20);
    Collections.sort(numbers, (Integer i1, Integer i2) -> i1.compareTo(i2));
    
    for(Integer i : numbers) {
      System.out.println(i);
    }
  }
}

In the code above the actual Lambda expression is only the following code.

(Integer i1, Integer i2) -> i1.compareTo(i2)

If you run the above class the output would be same as above.  However there are two things which have happened in the code. Firstly the number of lines of code has decreased and secondly code is also simpler to understand.  If you do not find it east then do not worry.  I will explain how to do it.

Steps to reduce anonymous class function call to Lambda expressions

There are only three conceptual things you need to take care while converting a function call to Lambda expression.

  1. You only need the parameter list on the left and method body on the right.
  2. Parameter and the method body will be separated by ->
  3. Remove everything else including name of the method and return type.  They are all inferred.  The return statement is also not needed as that is inferred.

Let us see the above steps in the following example where we will convert the function call to Lambda expression.

Collections.sort(numbers, new Comparator<Integer>(){
  public int compare(Integer i1, Integer i2){
    return i1.compareTo(i2);
  }
});

The anonymous class starts at new Comparator ...

Remove from new till end of compare.  You will have the following code.

Collections.sort(numbers, (Integer i1, Integer i2){
    return i1.compareTo(i2);
  }
});

Replace { with -> at the end of the first line. Also remove the return keyword at the beginning of second line as that is implicit.

Collections.sort(numbers, (Integer i1, Integer i2) ->
    i1.compareTo(i2);
  }
});

Last step is to remove the braces for the function ending and the anonymous class at the end.  After you remove here is the code.

Replace { with -> at the end of the first line.

Collections.sort(numbers, (Integer i1, Integer i2) ->
  i1.compareTo(i2);
);

Here is the code after formatting.

Collections.sort(numbers, (Integer i1, Integer i2) -> i1.compareTo(i2);
);