Lambda Expressions
A lambda is a short way to write a small function. It was the biggest Java 8 feature.
Before Java 8, passing a small piece of behaviour (like "how to compare two products") required a whole anonymous class - five or six lines of boilerplate. A lambda says the same thing in one line. This made Java code much shorter and opened the door to the Stream API.
Think of a lambda as a function you can store in a variable or pass to another method. On the left of the arrow are the inputs, on the right is what to do with them. Java works out the types from the context, so you rarely need to write them.
// parameters -> body
(a, b) -> a + b
price -> price * 0.9
() -> System.out.println("Hi")A lambda can be used wherever a functional interface is expected: an interface with exactly one abstract method. Java 8 gives you ready-made ones in java.util.function:
Predicate<T>: takes a value, returns true/false (test).Function<T,R>: takes a value, returns another (apply).Consumer<T>: takes a value, returns nothing (accept).Supplier<T>: takes nothing, returns a value (get).
These four interfaces cover most everyday needs: checking something (Predicate), converting something (Function), doing something with a value (Consumer) and producing a value (Supplier). Many Java library methods accept them, so once you know these, you can pass lambdas almost everywhere.
Method references
When a lambda only calls one method, you can write it shorter with :::
List<String> items = Arrays.asList("Pen", "Book");
items.forEach(s -> System.out.println(s));
items.forEach(System.out::println); // same thing- A lambda is a short anonymous function:
(params) -> body. - It can be used wherever a functional interface (one abstract method) is expected.
- Predicate, Function, Consumer and Supplier are the common ones.
- Method references like
System.out::printlnare an even shorter form.
