What was added to Java 8? Lambda expressions
With this article I start a short series that will explain what features were added to Java 8 update. Today I’ll focus on the major buzz of this release — lambda expression (a.k.a. lambdas).
These series will be divided into three parts (links will be updated once each blog post will be published):
Part 1. Lambda expression (current)
Lambda expression
When you start to learn Java and you have already passed command line examples you probably wants to create a desktop application. And for this you probably use JavaFX library.
In most of JavaFX applications we need to handle events that can be triggered by the users. For example, when they press a button it’ll create an Event object that need to be handled.
Therefore we need to assign an action which will be triggered once user click the button. For this task we usually declare anonymous inner class, which has only one method that performs necessary actions.
Even if above code is pretty straightforward it requires lots of writing and when code starts to grow it’s also becomes hard to ready. Luckily, thanks to lambda expression we can write it in a more compact way:
Whoa! That’s short, but what’s going on there?
Lambda expression syntax is made of three parts. First one are brackets, (e)
, that contains (or not) parameters of the abstract method of an anonymous inner class. It’s really important to remember that lamdas can be used only when a single abstract method.
In our case ActionEvent object is represented by e
reference. If the method doesn’t have any parameter we can use simple ()
instead, like for Runnable interface.
Finally method can have more than one arguments, like Comperator<T> interface method compare.
In above example we could also don’t include argument types (User), but for clarity reasons it good to be added.
Next, after the arguments there is a newly introduce right arrow ->
operator.
And finally there is a body of the implemented method. Usually it’s a one line of code, but if we require more we can surround it with {}
brackets.
If a method should return a value we can use return
statement as it’s in regular methods
Method reference (::)
Another topic that is tightly related and was introduced together with lambda expression is referencing the method. In short, with new operator ::
we can assign method to a reference, just like the object or primitive type. This approach allow us to extract the method from the object and pass it in another place without executing them.
Above we assign a hashCode method to a reference IntSupplier. Then it can be passed wherever we want in the code.
With method reference we can also assign static methods (without creating instance of the class) or constructor.