DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Trending

  • GenAI Isn't Solving the Problem Most Development Teams Actually Have
  • How to Set MX Records via API: Automate Email Routing Programmatically
  • 5 Warning Signs Your Data Architecture Needs a Redesign (Before It Falls Apart)
  • The Breach Was Never at the Door
  1. DZone
  2. Coding
  3. Java
  4. Java Comparators in a More Declarative Way

Java Comparators in a More Declarative Way

How to use the Comparator interface in Java 8 with a more intuitive and functional method.

By 
Yogen Rai user avatar
Yogen Rai
·
Jun. 12, 18 · Tutorial
Likes (24)
Comment
Save
Tweet
Share
19.7K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 has added many intuitive utility methods in the Comparator interface, making it easier to work with comparators in a functional way.

For example, if I want to sort the list of strings in a descending manner with length and they have the same length, I will sort in reverse natural ordering, and, I would, then, do something like this in JDK 7 or prior:

public void sortOldWay(final List < String > words) {
    words.sort(new Comparator < String > () {
        @Override
        public int compare(String s1, String s2) {
            if (s2.length() == s1.length()) {
                return s1.compareTo(s2);
            } else {
                return s2.length() - s1.length();
            }
        }
    });
}

You can see this approach is more imperative, focusing on how to sort the list.

But, with Java 8, rather than specifying how to do that, this can be accomplished in a more declarative way with static methodscomparing(), thenComparing() and   reverseOrder() as: 

public void sortNewWay(final List<String> words) {
        words.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()).reversed());
}

Comparator.comparing() takes a Function argument. The type T is the type of object being compared and type U is the type of object that will actually be compared. Here, T is thestring and, since we are comparing lengths of words, the type U   is Integer . So, it possible to write the call to sort even more intuitively as:

public void sortNewWayIntuitive(final List<String> words) {
        final Function<String, Integer> byLength = s -> s.length();
        words.sort(Comparator.comparing(byLength)
                .thenComparing(Comparator.reverseOrder()).reversed());
}


Let us take this to the next level where we want Comparator to work consistently with equals  for objects.

I want to sort the list of Student, where Student has a name and age, by name , then I need to consider age as well or vice versa, to make Comparators  consistent with equals as below:

public enum SORT_METHOD {
    BYNAME,
    BYAGE
}
public void sort(final List < Student > students, final SORT_METHOD method) {
    Collections.sort(students, (s1, s2) - > {
        if (SORT_METHOD.BYNAME == method) {
            if (s1.getName().compareTo(s2.getName()) == 0) {
                if (s1.getAge() == s2.getAge()) return 0;
                else if (s1.getAge() < s2.getAge()) return -1;
                else return 1;
            }
            return s1.getName().compareTo(s2.getName());
        } else {
            if (s1.getAge() == s2.getAge()) return s1.getName().compareTo(s2.getName());
            else if (s1.getAge() < s2.getAge()) return -1;
            else return 1;
        }
    });
}

This can be done in a more declarative way with comparing() and thenComparing() as:

public enum SORT_METHOD {
    BYNAME,
    BYAGE
}
Function < Student, String > byName = e - > e.getName();
Function < Student, Float > byAge = e - > e.getAge();

public void sort(final List < Student > students, final SORT_METHOD method) {
    if (SORT_METHOD.BYNAME == method) {
        Collections.sort(students, Comparator.comparing(byName).thenComparing(byAge));
    } else {
        Collections.sort(students, Comparator.comparing(byAge).thenComparing(byName));
    }
}

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

Conclusion

There are other utility methods like thenComparingDouble() , thenComparingLong() ,  reverseOrder(),  naturalOrder(),  reversed(), nullsFirst() , etc., making it the easiest comparison easiest. Let me know your thoughts!

For the examples I presented above, all the source code is available on GitHub.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook