Lambda expressions
Setting the scene: anonymous classes!
Lambdas are anonymous functions. They were added to Java since Java 8 was released. Lambdas can be used in any place a Single Abstract Method was used before.
Let's showcase the use of Lambdas through a demo.
We start with using anonymous inline classes.
Call usingAnonymousInlineClass
in main
and it must print out the sample authors sorted by name.
Lambda expression
An interface that only has one unimplemented abstract method is called functional interface in Java. In the example we saw above, Comparator
is a functional interface as it only has one unimplemented asbstract method named compare
that any implementing class must implement. We can use lambda expressions since Java 8 to implement a functional interface. In other words, we can just directly provide an implementation for the abstract method wherever a functional interface is expected. Alright, let's do the same thing we did above this time with a lambda function!
The following is syntax sugar for anonymous inline implementation of Comparator
.
You've used syntax sugar before: the enhanced for loop is syntax sugar for looping through the use of an iterator:
Bak to Lambdas, let's simplify our lambda expression:
tip
- You don't need to specify the data type of arguments.
- When the body of your lambda function is a single statement, you can eliminate the
{
}
and thereturn
keyword.
Also note the use of forEach
method: