Comparator.comparing() Method Example in Java 8

We will see a new way of building Comparators in Java 8 using Comparator comparing() method. This new way enables us writing very clean and very readable Comparator.

1) Example to Create a Comparator Old JDK7 Way

In our example we will create Comparator with old java 7 way, which will do sort Employees by last name property.

First we created simple Employee class holding firstName, lastName and age property and then we took Comparator Interface and provide implementation of it. Most of the time this implementation is an anonymous class and we take the instance of that anonymous class which is in our case is empComparatorByLastName. In most of the time our code will not work and it will get null pointer exception If Employee emp1 or Employee emp2 is null. So I will need to add some code to make sure that I don’t get this null pointer exception. I will also need to handle the case of comparison If Employee emp1 and Employee emp2 both are null, are they equal or should I say that they are different.

Output of the above programme after sorting by last name property:


2) Example to Create a Comparator Using comparing() Method New JDK8 Way

Now we get new static method comparing() on Comparator interface In jdk8.

What I do give to this comparing method(), I just give, what is called the keyExtractor. A keyExtractor is a regular function. It takes the instance of the object the Comparator will compare and extract the given field of that object. Now let’s write out old jdk7 code into jdk8 way for creating comparator.

So here Emplyoee::getLastName is just a lambda expression written with method reference. What doest it takes, method reference takes Employee as a parameter and return last name of that Employee. So what this Comparator do, it just compares the Employee using lastName property field. So this code is very much readable than previous code. By reading this code, anyone can easily understand that I am comparing Employee by lastName property field.

Output of the programme remain same as above programme.

Also check this post in which I am explaining the example of lambda expressions while using comparators, if you are working in java 8.


Leave a Reply

Your email address will not be published. Required fields are marked *