In the book OCP Study Guide there is this example about a Comparator that can be initialized in two ways. The first is via an anonymous class like this:
<
You can think of a lambda as a method that doesn't belong to a class, that can be passed around like a piece of data.
Or, with a very small mental shift, you can think of it as an object with only one method.
There is a set of interfaces marked as functional interfaces. This is mentioned in the Javadoc as:
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
That's a technical way of saying that because they have only one method, and they're marked as functional, the compiler can treat a lambda as an object with that interface. It knows to use the lambda as the implementation of the one method in the interface.
So you can do:
Comparator byNameComparator = (f1,f2) -> f1.name().compareTo(f2.name());
Predicate isVip = cust -> cust.orderCount > 20;
Callable- getResult = () -> queue.getItem();
Function
multiply = (a,b) -> a * b;
... and so on.
And wherever a parameter's type is a functional interface, you can instead use a lambda directly, so given:
public void sort(Comparator cmp);
... you can call it as:
foo.sort( (a,b) -> a.name().compareTo(b.name()));