How To Do Comparisons in Java 8

Posted By : Anil Kumar Maurya | 18-Jun-2018

In Java 8, there are many utility methods in the Comparator interface, which makes it easier to work with comparators in a functional way.
For example, if I want to sort the list of strings in a descending order of length. If they have the same length, I will sort in reverse natural ordering. In Java 7, we would have written below code:


public void oldSorting(List list){    
    Collections.sort(list, new Comparator() {
        @Override
        public int compare(String s1, String s2) {
            if (s2.length() == s1.length()) {
                return s1.compareTo(s2);
            } else {
                return s2.length() - s1.length();
            }
    }
    });
} 

 

As we can see this approach is more imperative. But by using Java 8 static methods comparing(), thenComparing() and reverseOrder() this can be accomplished in a more declarative way.

 

public static void newSorting(List list){        
    list.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()).reversed());
}

It is also possible to write the above code in a more intuitive way:

public void newSortingIntuitive(final List list) {
        final Function sortByLength = s -> s.length();
        list.sort(Comparator.comparing(sortByLength).thenComparing(Comparator.reverseOrder()).reversed());
}

Now, let's take this to the upper level, here we are going to compare objects. Suppose we have a person class which has name and age attributes. We want to sort a list of persons by their name. In Java 7, we would have written below code:

private void oldSorting(List persons) {        
    Collections.sort(persons, new Comparator() {
        @Override
        public int compare(Person p1, Person p2) {
            return p1.getName().compareTo(p2.getName());
        }
    });    
}

But In Java 8 we can write this in a more declarative approach:

private void newSorting(List persons) {
        
    persons.sort((Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));
    // or
    persons.sort((p1,p2) -> p1.getName().compareTo(p2.getName()));
    // or
    persons.sort(Comparator.comparing(Person::getName));

    // If we want further sorting on the basis of age
    persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
}

This is a more intuitive and functional method in comparison to the old technique.

Conclusion:
In Java8, there are more utility methods for comparing like reverseOrder(),  naturalOrder(),  reversed(), nullsFirst() , thenComparingDouble() , thenComparingLong() , etc., which makes comaprison easier to progammer.

About Author

Author Image
Anil Kumar Maurya

Anil is an experienced Lead with core knowledge of Java, Spring, and SQL. He has good working experience in banking, finance and trading domain.

Request for Proposal

Name is required

Comment is required

Sending message..