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

  • Migrating My Java Codebase to EE10
  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo

Trending

  • Everything About HTTPS and SSL in Java
  • Choosing a BBD Framework
  • Spring Boot's Hidden Secret for Configuration: EnvironmentPostProcessor
  • When 12 Hours of Offline Changes Collide: Designing Conflict-Safe Mobile Sync

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
·
Jun. 12, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
19.9K 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

  • Migrating My Java Codebase to EE10
  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

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