Comparator.thenComparing() Method Example in Java 8

We will see a new way of Comparators Chaining in Java 8 using Comparator Interface thenComparing() method. This new way enables us writing very clean and very readable Comparator chaining logic.

Comparator Chaining Example Old JDK 7 Way

In our example we will create Comparator with old java 7 way, which will do sort Employees by last name property. What If I want to chain Comparators? Let say first compare it by Employee last name property and If last name is equal then compare it by Employee first name property.

Output of the Comparator chaining logic old Java 7 way:

If I need to write the code in this way, this quickly become cluttered code, not much readable. If someone else need to work on this code, I need to provide some kind of documentation or remark for his/her understanding. I also need to check If Employee emp1 or Employee emp2 is null, or what If Employee emp1 and Employee emp2 both are null at the same time.

Comparator Chaining Example New JDK8 Way

Now we get new default method thenComparing () on Comparator Interface in jdk8.

Let write our above Comparator Chaining logic in new Java 8 way.

The output of the new Java 8 Comparator chaining logic  same as above programme:

Comparator.thenComparing() method takes same types of argument as Comparator.comparing() method and it will just chain the comparison of Employee last name and If last name are equals then compare the Employee using first name. So this is much better code as it is easier to read. I don’t need to document this code as by reading this people will understand what the code is doing.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.