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:
@FunctionalInterfacepublicinterfaceComparator<T>{// Only one abstract method allowedintcompare(To1,To2);// Overriding allowedbooleanequals(Objectobj);// Optional default methods allowed}
λEs Syntax and Example
Lambda expressions typically include a parameter list, a return type, and a body:
(parameterlist)->{statements;}
Examples of λEs include the following:
()->66(x,y)->x+y(Integerx,Integery)->x*y(Strings)->{System.out.println(s);}
This simple JavaFX GUI application adds ...