14 03 Lambda expression
Lambda expressions were added to the Java language to write small pieces of behaviour in a more compact way. A lambda is similar to a method but you do not need to declare a name for it: you can write the body directly. It can take no parameter, a single parameter without parentheses, or several parameters wrapped in parentheses and separated by commas.
To see this in practice we create a simple list, for example a list of numbers, and we want to print each value. With the new forEach method we pass a lambda: list.forEach(n -> System.out.println(n));. The parameter n represents one element of the list, and the body of the lambda is the block of code that should run for it. This single line replaces the classic for loop with an index.
Storing a lambda in a variable
A lambda is not limited to being passed inline. We can store it in a variable whose type is the functional interface Consumer. For instance: Consumer<Integer> print = n -> System.out.println(n);. Once defined, calling list.forEach(print); produces exactly the same output.
- No parameter:
() -> System.out.println("hello"). - One parameter (no parentheses needed):
n -> System.out.println(n). - Multiple parameters (parentheses needed):
(a, b) -> a + b.
Lambdas pair very well with collections and streams in Java, because they let us express the operation we want without writing boilerplate iteration code. They are the foundation of more advanced topics like the Streams API, which we will explore later.