Why Lambda Expressions
Description
The lambda expressions allows us to pass logic in a compact way.
Example
The following code uses an anonymous inner class to add event handler for a button click action.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hi");
}// w w w . jav a 2s. c o m
});
The action handler prints out a message when that the button is clicked.
By using a lambda expression we can add the action handler to a button click event in a single line of code.
button.addActionListener(e -> System.out.println("hi"));
Note
Instead of passing in an inner class that implements an interface, we're passing in a block of code.
e
is the name of a parameter,
->
separates the parameter from the body of
the lambda expression.
In the lambda expression the parameter e
is not
declared with a type. javac
is inferring the type of
e
from its context, the signature of addActionListener
.
We don't need to explicitly write out the type when it's obvious. The lambda method parameters are still statically typed.