Lambda Expressions and Method References
Join the DZone community and get the full member experience.Join For Free
Hello, friends this my first article on Java 8.
Today, I am going to share how lambda expressions and method references reduce boilerplate code and make our code more readable and compact. Suppose we have a
Student class that has two fields,
age. We are going to sort a student list with the help of the
Comparator interface. After that, we will reduce the code step-by-step with the help of some of Java 8's new features.
This is our
Student class, with their two fields and getter and setter methods. We are overriding the
toString method of the
Suppose we have
studentlist that we are going to sort. We know that
List provides a
sort method and
It expects a
Comparator object as an argument to compare two
You may also like: Functional Programming Patterns With Java 8.
Step 1: Create Custom StudentComparator to Pass Into the Sort Method
The solution looks like this:
Step 2: Use an Anonymous Class
Rather than implementing
Comparator for the purpose of instantiating it once, we could use an anonymous class to improve our solution. The solution looks like this:
Step 3: Use Lambda Expressions
Our current solution is still verbose. Java 8 introduces lambda expressions, which provide a lightweight syntax to achieve the same goal.
We know that lambda expression can be used where a functional interface is expected: a functional interface is an interface defining only one abstract method.
The signature of the abstract method (called function descriptor) can describe the signature of a lambda expression. In our case, the
Comparator represents a function descriptor
(T, T) -> int.
Because we’re using
Student, it represents more specifically,
(Student, Student) -> int. Our improved solution looks like the following code snippet:
We can write our solution like this:
Java's compiler could infer the types of the parameters of a lambda expression by using the context in which the lambda appears. So, we can avoid the use of types of parameters.
Can we make our code even more readable? Yes,
Comparator has a static helper method called,
comparing, that takes a function extracting a
Comparable key and produces a
We can now rewrite our solution in a slightly more compact form:
Step 4: Use Method References
We can use a method reference to make our code slightly less verbose:
Congratulations, this is our final solution!
It’s shorter; it’s also obvious what it means, “sort Student comparing the age of the Student.” This is how Java 8 makes code more readable and compact.
If you have any doubts, feel free to ask me in the comment section below. Have a nice day.
Reference: Java 8 in Action.
Opinions expressed by DZone contributors are their own.