Java 8 introduced Lambda expressions. Lambda expressions are a shorthand for implementing single method interfaces. By a single method interface, I mean something like the following.
Flower has a single method called
bloom(). Before Lambda expressions, we could implement single method interfaces with an anonymous class or with a normal class.
Here is an example of implementing a single method interface named
Flower with a traditional class.
Here’s an example of implementing a single method interface named
Flower with an anonymous class.
Whether you use an anonymous class, or a full blown class to implement the single method interface, there’s a lot of work do before you even get around to writing the code that goes in the single method you want implemented.
Lambda expressions remove all this extra work.
First we make a small change to the original interface definition. We add the
@FunctionalInterface annotation to the interface’s method. The
Flower interface changes to look like the following code.
Now we modify the anonymous class to look like the following.
Notice that the anonymous class went from,
to a Lambda expression that looks like the following.
Why yes, … this is the coolest thing since sliced bread.
Using a Lambda expression, you don’t have to tell the Java compiler that you are implementing a
Flower, or that you are implementing the
bloom() method. The compiler is smart enough to know the class and the method you are implementing without the added hassle of telling it.
Now for the variations.
If you are passing parameters into the implemented method, place those arguments in the parens of the Lambda expression. For example,
You can specify the argument types for clarity.
You can implement multi-line methods using curly braces. Don’t forget your semicolons for line endings in code blocks.
If the method you are implementing has only one parameter of an obvious type, you can ignore the initial parens, like the following example.
That’s all the basics of Java 8’s Lambda expressions. They have a lot of power besides just replacing anonymous classes, but that’s the subject of a more advanced tutorial.