Lambda Expressions

Learn about lambda expressions and their syntax.

Introduction

The biggest new feature of Java 8 is the language level support for lambda expressions (Project Lambda). A lambda expression is like syntactic sugar for an anonymous class with one method whose type is inferred. However, it will have huge implications for simplifying development.

Syntax

The main syntax of a lambda expression is parameters -> body. The compiler can usually use the context of the lambda expression to determine the functional interface being used and the type of the parameters. There are four important rules to the syntax:

  • Declaring the type of the parameters is optional.
  • Using parentheses around the parameter is optional if we have only one parameter.
  • Using curly braces is optional (unless we need multiple statements).
  • The return keyword is optional if we have a single expression that returns a value.

Here are some examples of the syntax:

() -> System.out.println(this) 

(String str) -> System.out.println(str) 

str -> System.out.println(str) 

(String s1,String s2) -> {return s2.length() - s1.length();} 

(s1,s2) -> s2.length() -  s1.length()

The last expression could be used to sort a list. For example:

Arrays.sort(strArray,
  (String s1, String s2) -> s2.length() - s1.length());

In this case, the lambda expression implements the Comparator interface to sort strings by length.

Scope

Here’s a short example of using lambdas with the Runnable interface:

Press + to interact
import static java.lang.System.out;
public class Hello {
Runnable r1 = () -> out.println(this);
Runnable r2 = () -> out.println(toString());
public String toString() { return "Hello, world!"; }
public static void main(String[] args) {
new Hello().r1.run(); //Hello, world!
new Hello().r2.run(); //Hello, world!
}
}

The important thing to note is that both the r1 and r2 lambdas call the toString() method of the Hello class. This demonstrates the scope available ...