INTRODUCTION TO LAMBDA
EXPRESSION
Chonlameth ARPNIKANONDT, Ph.D.
Our MAIN text >>>
We also rely on other sources for
additional information.
2
METHOD PARAMETERIZATION
3
1. Filtering Green Apples
4
2. Parameterizing the Color
5
What if…
6
3. Filtering with every attribute one can think of
7
Here comes… Behavior Parameterization
8
4. Filtering by abstract criteria
Pattern at play here?
9
10
11
12
Verbose!
13
5. Using an anonymous class
14
15
6. Using a Lambda expression
16
7. Abstracting over a List type
17
LAMBDA EXPRESSIONS IN A NUTSHELL
18
19
Lambda comes from Lambda Calculus
• It technically do NOT let you do anything that you could NOT do prior to Java 8
• It encourages you to adopt the style of behavior parameterization
• Your code becomes clearer and more flexible
20
21
22
Basic Syntax of a Lambda
• Expression-style lambda
• Block-style lambda
23
Food for thought…
24
Lambda Use Cases and Examples
25
Where and how to use lambdas…
• You can use a lambda expression in the context of a functional interface…
Here, you can pass a lambda as second
argument to the method filter because it expects an object of type
Predicate<T>,
which is a functional interface.
26
Functional Interfaces
27
Functional Interfaces
A functional interface is an interface that
specifies exactly one abstract method.
28
29
This is COMPATIBLE with
30
Which of these are functional interfaces?
31
Function Descriptor
• In each functional interface, there is exactly one (1) abstract method…
• We call this abstract method a function descriptor…
• It describes the signature of the lambda expression
• The Runnable interface, for example, has one abstract method called run, which accepts
nothing and returns nothing (void).
• Compatible with lambda: () -> void
• The parameter list () means: It accepts nothing…
• The keyword void means: It returns nothing…
• (Apple, Apple) -> int denotes a function taking two Apples as parameters and returning an int.
32
Noteworthy…
33
Which of the following are valid uses of lambda expressions?
Note: Callable<T> has the
function descriptor (lambda-
expression signature) of
() -> T
34
Example: The Execute-Around Pattern
35
1. Recognize behavior parameterization…
You can have a lambda help you pass the behavior, e.g.
36
2. Use a functional interface to pass behaviors…
Recall, lambdas can be used only in the context of a functional interface
Will have to create one that matches the signature BufferedReader -> String
and that may throw an IOException.
37
3. Execute the behavior
38
4. Pass lambdas…
39
Recap: Functional Interfaces…
• Functional interfaces are useful because the signature of the abstract method can describe the
signature of a lambda expression.
• The signature of the abstract method of a functional interface is called a function descriptor.
• In order to use different lambda expressions, you need a set of functional interfaces that can
describe common function descriptors.
• Several functional interfaces are already available in the Java API such as Comparable,
Runnable, and Callable.
• Java 8 includes several new functional interfaces in the [Link] package, e.g.
•
40
Predicate
41
Consumer
42
Function
43
Consider this…
Comments?
Image source (top): [Link]
Image source (bottom): [Link]
44
Primitive Specialization
45
46
47
Lambda Use Cases and Examples with Functional Interfaces
48
Exceptions, lambdas and functional interfaces….
49
Deconstructing
the type-
checking
process of a
lambda
expression
50
Same lambda, different functional interfaces…
51
Some notes (to help avoid confusion) ☺
The method add of a List
returns a boolean and NOT void….
52
Which will get executed calling execute( () -> {} ) ?!!
53
Which will get executed calling execute( () -> {} ) ?!!
A cast is needed! execute((Action)() -> {} );
54
Type inference
Another example…
55
Capturing Lambdas
• Lambdas are allowed to capture (to reference in their bodies) instance variables and static
variables without restrictions.
• When local variables are captured, they have to be explicitly declared final or be
effectively final.
• Lambda expressions can capture local variables that are assigned to only once.
Note: capturing an instance variable can be seen as capturing the final local variable this.
Image source: [Link]
56
Capturing Lambdas
?
• Lambdas are allowed to capture (to reference in their bodies) instance variables and static
variables without restrictions.
• When local variables are captured, they have to be explicitly declared final or be
effectively final.
• Lambda expressions can capture local variables that are assigned to only once.
Note: capturing an instance variable can be seen as capturing the final local variable this.
57
METHOD REFERENCES
58
Method References: Revisited
59
Method References
• Method references can be seen as shorthand for lambdas calling only a specific method
• A method reference lets you create a lambda expression from an existing method implementation.
• Code can gain better readability by referring to a method name explicitly
• Target reference is placed before the delimiter ::
• Name of the method is provided after this delimiter (::)
• Apple::getWeight is a method reference to the method getWeight defined in the Apple class.
• This method reference is shorthand for the lambda expression
(Apple apple) -> [Link]()
60
Examples of lambdas and method reference equivalents
61
This type refers to a method to an object that will be supplied as
one of the parameters of the lambda.
This type refers to a situation when you’re calling a method in a
lambda to an external object that already exists.
This method reference is particularly useful when you need to pass
around a method defined as a private helper.
62
63
Which type of method references?
A good functional interface ?
64
Constructor Reference (1) – ClassName::new
65
Constructor Reference (2) – ClassName::new
66
Constructor Reference (3) – ClassName::new
67
Lambdas and Method References in Action – An Example
• Continue with the initial problem of sorting a list of Apples with different ordering strategies
• Final solution will look like this:
• Will employ the available Comparator interface supplied by Java (8 onward)
68
1. Passing code (1st solution)
69
2. Using an anonymous class (2nd solution)
70
3. Using lambda expressions (a review)
Given the code above, the is the functional descriptor
of the Comparator interface?
71
3. Using lambda expressions (3rd solution)
Comparator includes a static helper method called comparing that takes a Function
extracting a Comparable key and produces a Comparator object
72
4. Using method reference (final solution)
73