λ basic syntax
Let's take a look at the basic lambda syntax.
A lambda is basically an anonymous block of functionality. It's a lot like using an anonymous class instance. For example, if we want to sort an array in Java, we can use the Arrays.sort
method which takes an instance of the Comparator
interface.
It would look something like this:
Arrays.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer first, Integer second) { return first.compareTo(second); } });
The Comparator
instance here is a an abstract piece of the functionality; it means nothing on its own; it's only when it's used by the sort
method that it has purpose.
Using Java's new syntax, you can replace this with a lambda which looks like this:
Arrays.sort(numbers, (first, second) -> first.compareTo(second));
It's a more succinct way of achieving the same thing. In fact, Java treats this as if it were an instance of the Comparator
class. If...