How do lambda expressions work in Java, and what are the parts of one?
A lambda expression is a short way of writing a function without giving it a name and without writing a class for it.
It has three parts. The first part is the list of parameters, in brackets. The second part is the arrow, which is the two characters ->. The third part is the body, which is either one expression or a block of statements.
import java.util.function.Function;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
// One parameter, one expression.
Function<String, Integer> length = text -> text.length();
System.out.println("length : " + length.apply("hello"));
// One parameter, a block of statements.
Function<String, String> shout = text -> {
String result = text.toUpperCase();
return result + "!";
};
System.out.println("shout : " + shout.apply("hello"));
// No parameters at all.
Supplier<String> greeting = () -> "hello from a lambda";
System.out.println("greeting : " + greeting.get());
}
}
When the compiler sees a lambda, it works out which interface it belongs to from where you are putting it. That interface has to have exactly one method that is not already implemented, and the parameters of that method are the parameters of the lambda and the return type of that method is what the lambda gives back.
One detail that makes the code easier to read is that you can leave out the types of the parameters when they are obvious. The compiler works them out from the interface.
The next question in this topic looks at what happens when the parameters do not match.