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.
@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:
()->66(x,y)->x+y(Integerx,Integery)->x*y(Strings)->{System.out.println(s);}
This simple JavaFX GUI application adds text to the title bar when the button is pressed. The code makes use ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access