欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 8 Comparator: How to Sort a List

程序员文章站 2022-03-24 19:04:27
...

 

文章地址: https://dzone.com/articles/java-8-comparator-how-to-sort-a-list

 

 

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

 
 
 
 
1
List<String> cities = Arrays.asList(
2
       "Milan",
3
       "london",
4
       "San Francisco",
5
       "Tokyo",
6
       "New Delhi"
7
);
8
System.out.println(cities);
9
//[Milan, london, San Francisco, Tokyo, New Delhi]
10
11
cities.sort(String.CASE_INSENSITIVE_ORDER);
12
System.out.println(cities);
13
//[london, Milan, New Delhi, San Francisco, Tokyo]
14
15
cities.sort(Comparator.naturalOrder());
16
System.out.println(cities);
17
//[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.

Sort a List of Integers

 
 
 
 
1
List<Integer> numbers = Arrays.asList(6, 2, 1, 4, 9);
2
System.out.println(numbers); //[6, 2, 1, 4, 9]
3
4
numbers.sort(Comparator.naturalOrder());
5
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.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings"),
3
        new Movie("Back to the future"),
4
        new Movie("Carlito's way"),
5
        new Movie("Pulp fiction"));
6
7
movies.sort(Comparator.comparing(Movie::getTitle));
8
9
movies.forEach(System.out::println);
 
 

The output will be:

 
 
 
 
1
Movie{title='Back to the future'}
2
Movie{title='Carlito's way'}
3
Movie{title='Lord of the rings'}
4
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.

 
 
 
 
1
return (Comparator<T> & Serializable)
2
            (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.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8),
3
        new Movie("Back to the future", 8.5),
4
        new Movie("Carlito's way", 7.9),
5
        new Movie("Pulp fiction", 8.9));
6
7
movies.sort(Comparator.comparingDouble(Movie::getRating)
8
                      .reversed());
9
10
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. 

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8, true),
3
        new Movie("Back to the future", 8.5, false),
4
        new Movie("Carlito's way", 7.9, true),
5
        new Movie("Pulp fiction", 8.9, false));
6
7
movies.sort(new Comparator<Movie>() {
8
    @Override
9
    public int compare(Movie m1, Movie m2) {
10
        if(m1.getStarred() == m2.getStarred()){
11
            return 0;
12
        }
13
        return m1.getStarred() ? -1 : 1;
14
     }
15
});
16
17
movies.forEach(System.out::println);
 
 

The result will be:

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

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

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

We can also use Comparator.comparing() again:

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

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.

 
 
 
 
1
List<Movie> movies = Arrays.asList(
2
        new Movie("Lord of the rings", 8.8, true),
3
        new Movie("Back to the future", 8.5, false),
4
        new Movie("Carlito's way", 7.9, true),
5
        new Movie("Pulp fiction", 8.9, false));
6
7
movies.sort(Comparator.comparing(Movie::getStarred)
8
                      .reversed()
9
                      .thenComparing(Comparator.comparing(Movie::getRating)
10
                      .reversed())
11
);
12
13
movies.forEach(System.out::println);
 
 

And the output is:

 
 
 
 
1
Movie{starred=true, title='Lord of the rings', rating=8.8}
2
Movie{starred=true, title='Carlito's way', rating=7.9}
3
Movie{starred=false, title='Pulp fiction', rating=8.9}
4
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.