“A lambda expression is like a method: it provides a list of formal parameters and a body—an expression or block—expressed in terms of those parameters,” says JSR 335.
(int x, int y) -> {
return x + y;
}
The curly braces are optional if the body contains only a single expression:
(int x, int y) -> x+y
Parameters can be either declared-typed or inferred-typed:
(x, y) -> x+y // Inferred-type parameters
The parentheses are optional for single inferred-type parameter:
(x) -> x+1 // Single inferred-type parameter
x -> x+1 // Parens optional for single inferred-type case
x -> x+1 // Parens optional for single inferred-type case
Parentheses are required if there are no parameters:
() -> 42 // No parameters, expression body
() -> { System.gc(); } // No parameters, void block body
() -> { System.gc(); } // No parameters, void block body
Use Cases
Lambda expressions can be assigned to a functional interface.
Comparator<Person> sortByAge = (p, q) -> p.getAge() > q.getAge();
They can also be directly used as a function variable.
button.addActionListener(e -> {
System.out.println("Handled by Lambda")
});
Collections.sort(list, (p, q) -> p.getAge() > q.getAge());
Method References
The lambda expression can be replaced with a method references.
Collections.sort(list, Person::compareByAge); //static method reference
Person p = new Person();
Collections.sort(list, p::compareByAge); //instance method reference
Collections.sort(list, p::compareByAge); //instance method reference
References
Examples are based on or copied from the following references:
No comments:
Post a Comment