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, name
and 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 Object
class.
xxxxxxxxxx
class Student {
private String name;
private Integer age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
Suppose we have studentlist
that we are going to sort. We know that List
provides a sort
method and signature
like:
xxxxxxxxxx
void sort(Comparator<? super E> c)
It expects a Comparator
object as an argument to compare two Students
!
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:
xxxxxxxxxx
public class StudentComparator implements Comparator<Student> {
public int compare(Student s1, Student s2){
return s1.getAge().compareTo(s2.getAge());
}
}
studentlist.sort(new StudentComparator());
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:
xxxxxxxxxx
studentlist.sort(new Comparator<Student>(){
public int compare(Student s1, Student s2){
return s1.getAge().compareTo(s2.getAge());
}
});
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:
xxxxxxxxxx
studentlist.sort((Student std1, Student std2) -> std1.getAge().compareTo(std2.getAge()));
We can write our solution like this:
xxxxxxxxxx
studentlist.sort((std1, std2) -> std1.getAge().compareTo(std2.getAge()));
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 Comparator
object.
We can now rewrite our solution in a slightly more compact form:
xxxxxxxxxx
import static java.util.Comparator.comparing;
studentlist.sort(comparing((std) -> std.getAge()));
Step 4: Use Method References
We can use a method reference to make our code slightly less verbose:
xxxxxxxxxx
static import of java.util.Comparator.comparing
studentlist.sort(comparing(Student::getAge));
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.
Further Reading
Opinions expressed by DZone contributors are their own.
Trending
-
Mainframe Development for the "No Mainframe" Generation
-
Is Podman a Drop-in Replacement for Docker?
-
Explainable AI: Making the Black Box Transparent
-
Incident Response Guide
Comments