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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Memory Leak Due To Mutable Keys in Java Collections
  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Squid Game: The Clean Code Trials — A Java Developer's Survival Story
  • Jakarta EE 11 and the Road Ahead With Jakarta EE 12

Trending

  • Docker Model Runner: Running AI Models Locally Made Simple
  • Modernize Your IAM Into Identity Fabric Powered by Connectors
  • Stabilizing ETL Pipelines With Airflow, Presto, and Metadata Contracts
  • Server-Driven UI: Agile Interfaces Without App Releases
  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.4K 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

  • Memory Leak Due To Mutable Keys in Java Collections
  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Squid Game: The Clean Code Trials — A Java Developer's Survival Story
  • Jakarta EE 11 and the Road Ahead With Jakarta EE 12

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: