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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Where Should a Transaction End? Designing Consistency Boundaries in Distributed Java Systems

Trending

  • Building IoT Time-Series Applications With Java and Apache IoTDB
  • Genkit Flows as senro Steps: Extremely Powerful AI Pipelines in Go
  • Stop Paying a Model to Make Decisions You Already Made
  • Rebuilding Elasticsearch Under Load: Unsafe Watermarks and a Sampling Blind Spot

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
19.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Where Should a Transaction End? Designing Consistency Boundaries in Distributed Java Systems

Partner Resources

×

Comments

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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