Chapter 19. Lambda Expressions

Lamda expressions (λEs), also known as closures, provide a means to represent anonymous methods. Supported by Project Lambda, λEs allow for the creation and use of single method classes. These methods have a basic syntax that provides for the omission of modifiers, the return type, and optional parameters. The specification for λEs is set out in JSR 335, which is divided into seven parts: functional interfaces, lambda expressions, method and constructor references, poly expressions, typing and evaluation, type inference, and default methods. This chapter focuses on the first two.

λEs Basics

λEs must have a functional interface (FI). An FI is an interface that has one abstract method and zero or more default methods. FIs provide target types for lambda expressions and method references, and ideally should be annotated with @FunctionalInterface to aid the developer and compiler with design intent.

public interface Comparator<T> {
  // Only one abstract method allowed
  int compare(T o1, T o2);
  // Overriding allowed
  boolean equals(Object obj);
  // Optional default methods allowed

λEs Syntax and Example

Lambda expressions typically include a parameter list, a return type, and a body.

(parameter list) -> { statements; }

Examples of λEs include:

() -> 66
(x,y) -> x + y
(Integer x, Integer y) -> x*y
(String s) -> { System.out.println(s); }

This simple JavaFX GUI application adds text to the title bar when the button is pressed. The code makes use ...

Get Java 8 Pocket Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.