O'Reilly logo

Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 19. Lambda Expressions

Lambda 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, as shown in the following code example:

@FunctionalInterface
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 the following:

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

This simple JavaFX GUI application adds ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required