Video in progress
What is a lambda expression and what is its syntax?
A lambda is a short anonymous function: parameters, an arrow -> and a body. It implements the single abstract method of a functional interface and is a much shorter form of an anonymous class.
📖 Answer
Before Java 8, writing a comparator needed an anonymous class:
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
With a lambda the same thing is one line:
list.sort((a, b) -> a.length() - b.length());
Syntax variants:
x -> x * 2: one parameter, no parentheses;(a, b) -> a + b: several parameters;() -> System.out.println("salom"): no parameters;(String s) -> s.isBlank(): the type written explicitly;- if the body is several lines, you need braces and
return:x -> { int y = x + 1; return y * y; }.
The compiler usually infers parameter types from context, so you don't have to write them.
Sign up to mark studied questions and save your progress.