Comparator in Java8

Comparator is comparatively easy to use in Java8. Functional style of programming in Java8 has introduced new way to use the comparator.

This is what we we do before Java8. Kindly note that getDob() method returns date of birth of a Student, which is java.util.Date instance.

studentList.sort(new Comparator<Student>() {

     @Override
     public int compare(Student o1, Student o2) {
         return o1.getDob().compareTo(o2.getDob());
     }
});

Here we can see that we have to create the anonymous class of comparator and then we provide the sorting logic.  With Java8 we can use Lambada expression to reduce the extra boiler plate code of comparator declaration and compare method declaration.

studentList.sort((o1, o2) ->  {
    return o1.getDob().compareTo(o2.getDob());
});

You can see how it is reduced in size. Even more there are lot of default methods has been introduced in Comparator interface. For example,

studentList.sort(Comparator.comparing(Student::getDob));

Here comparing method will prepare the comparator based on the method reference we have provided. Moreover, we can also simply reverse the order of sorting,

studentList.sort(Comparator.comparing(Student::getDob).reversed());

Lot more default methods are there in Comparator interface to reduce the extra code of comparator declaration and speed up the development.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s