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
Please enter at least three characters to search
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?
  • Functional Approach To String Manipulation in Java

Trending

  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Chaos Engineering for Microservices
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Comparator: How to Sort a List

Java 8 Comparator: How to Sort a List

Want to sort your Lists? Look no further. Check out the variety of ways you can get your Lists just the way you want them.

By 
Mario Pio Gioiosa user avatar
Mario Pio Gioiosa
·
Updated May. 20, 19 · Tutorial
Likes (67)
Comment
Save
Tweet
Share
587.0K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we’re going to see several examples on how to sort a List in Java 8.

Sort a List of Strings Alphabetically

List<String> cities = Arrays.asList(
       "Milan",
       "london",
       "San Francisco",
       "Tokyo",
       "New Delhi"
);
System.out.println(cities);
//[Milan, london, San Francisco, Tokyo, New Delhi]

cities.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(cities);
//[london, Milan, New Delhi, San Francisco, Tokyo]

cities.sort(Comparator.naturalOrder());
System.out.println(cities);
//[Milan, New Delhi, San Francisco, Tokyo, london]

We’ve written London with a lowercase "L" to better highlight differences between Comparator.naturalOrder(), which returns a Comparator that sorts by placing capital letters first, and String.CASE_INSENSITIVE_ORDER, which returns a case-insensitive Comparator.

Basically, in Java 7, we were using Collections.sort() that was accepting a List and, eventually, a Comparator –  in Java 8 we have the new List.sort(), which accepts a Comparator.


The Premium Java Programming Certification Bundle*

*Affiliate link. See Terms of Use.

Sort a List of Integers

List<Integer> numbers = Arrays.asList(6, 2, 1, 4, 9);
System.out.println(numbers); //[6, 2, 1, 4, 9]

numbers.sort(Comparator.naturalOrder());
System.out.println(numbers); //[1, 2, 4, 6, 9]

Sort a List by String Field

Let’s suppose we have our Movie class and we want to sort our List by title. We can use Comparator.comparing() and pass a function that extracts the field to use for sorting – title, in this example.

List<Movie> movies = Arrays.asList(
        new Movie("Lord of the rings"),
        new Movie("Back to the future"),
        new Movie("Carlito's way"),
        new Movie("Pulp fiction"));

movies.sort(Comparator.comparing(Movie::getTitle));

movies.forEach(System.out::println);

The output will be:

Movie{title='Back to the future'}
Movie{title='Carlito's way'}
Movie{title='Lord of the rings'}
Movie{title='Pulp fiction'}

As you’ve probably noticed, we haven’t passed a Comparator, but the List is correctly sorted. That’s because title, the extracted field, is a String, and a String implements a Comparable interface. If you peek at the Comparator.comparing() implementation, you will see that it calls compareTo on the extracted key.

return (Comparator<T> & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));  

Sort a List by Double Field

In a similar way, we can use Comparator.comparingDouble() for comparing double value. In the example, we want to order our List of movies by rating, from the highest to the lowest.

List<Movie> movies = Arrays.asList(
        new Movie("Lord of the rings", 8.8),
        new Movie("Back to the future", 8.5),
        new Movie("Carlito's way", 7.9),
        new Movie("Pulp fiction", 8.9));

movies.sort(Comparator.comparingDouble(Movie::getRating)
                      .reversed());

movies.forEach(System.out::println);

We used the reversed function on the Comparator in order to invert default natural order; that is, from lowest to highest. Comparator.comparingDouble() uses Double.compare() under the hood.

If you need to compare int or long, you can use comparingInt() and comparingLong() respectively.

Sort a List With a Custom Comparator

In the previous examples, we haven’t specified any Comparator since it wasn’t necessary, but let’s see an example in which we define our own Comparator. Our Movie class has a new field – “starred” – set using the third constructor parameter. In the example, we want to sort the list so that we have starred movies at the top of the List. 

List<Movie> movies = Arrays.asList(
        new Movie("Lord of the rings", 8.8, true),
        new Movie("Back to the future", 8.5, false),
        new Movie("Carlito's way", 7.9, true),
        new Movie("Pulp fiction", 8.9, false));

movies.sort(new Comparator<Movie>() {
    @Override
    public int compare(Movie m1, Movie m2) {
        if(m1.getStarred() == m2.getStarred()){
            return 0;
        }
        return m1.getStarred() ? -1 : 1;
     }
});

movies.forEach(System.out::println);

The result will be:

Movie{starred=true, title='Lord of the rings', rating=8.8}
Movie{starred=true, title='Carlito's way', rating=7.9}
Movie{starred=false, title='Back to the future', rating=8.5}
Movie{starred=false, title='Pulp fiction', rating=8.9}

We can, of course, use a lambda expression instead of Anonymous class, as follows:

movies.sort((m1, m2) -> {
    if(m1.getStarred() == m2.getStarred()){
        return 0;
    }
    return m1.getStarred() ? -1 : 1;
});

We can also use Comparator.comparing() again:

movies.sort(Comparator.comparing(Movie::getStarred, (star1, star2) -> {
    if(star1 == star2){
         return 0;
    }
    return star1 ? -1 : 1;
}));

In the last example, Comparator.comparing() takes the function to extract the key to use for sorting as the first parameter, and a Comparator as the second parameter. This Comparator uses the extracted keys for comparison; star1 and star2 are boolean and represent m1.getStarred() and m2.getStarred() respectively.

Sort a List With Chain of Comparators

In the last example, we want to have starred movie at the top and then sort by rating.

List<Movie> movies = Arrays.asList(
        new Movie("Lord of the rings", 8.8, true),
        new Movie("Back to the future", 8.5, false),
        new Movie("Carlito's way", 7.9, true),
        new Movie("Pulp fiction", 8.9, false));

movies.sort(Comparator.comparing(Movie::getStarred)
                      .reversed()
                      .thenComparing(Comparator.comparing(Movie::getRating)
                      .reversed())
);

movies.forEach(System.out::println);

And the output is:

Movie{starred=true, title='Lord of the rings', rating=8.8}
Movie{starred=true, title='Carlito's way', rating=7.9}
Movie{starred=false, title='Pulp fiction', rating=8.9}
Movie{starred=false, title='Back to the future', rating=8.5}

As you’ve seen, we first sort by starred and then by rating – both reversed because we want highest value and true first.

Sort (Unix) Java (programming language) Strings Sorting

Published at DZone with permission of Mario Pio Gioiosa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Hibernate Validator vs Regex vs Manual Validation: Which One Is Faster?
  • Functional Approach To String Manipulation in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

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
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!