Java8 comparator, how to sort the List, java8list
In this article, we will see several examples of how to sort the List in Java 8.
I. Sort the string list by letter
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]
London's "L" uses lowercase letters to better highlight Comparator. naturalOrder () (returns the comparator that first sorts uppercase letters) and String. CASE_INSENSITIVE_ORDER (returns a case-insensitive comparator.
Basically, in Java 7, we use Collection. sort () to accept the List and the final Comparator -- in Java 8, we have a new List. sort () to accept Comparator.
Ii. Sort the integer list
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]
3. Sort the list by string Fields
Suppose we have a Movie class, and we want to sort the List by title. We can use Comparator. comparing () to pass a function. The function extracts the fields used to sort titles-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 );
Output:
Movie {title = 'back to the ure '}
Movie {title = 'carlito's way '} Movie {title = 'Lord of the rings'} Movie {title = 'pulp fiction '}
You may notice that we didn't use any Comparator, but sorted the List correctly. This is because the title-extracted field-is a string that implements a comparable interface. If you look 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 ));
4. Sort the list by double Field
In a similar way, we can use Comparator. comparingDouble () to compare double values. In this example, we want to order the Movie list based on the highest to lowest score.
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 use the reversed function on Comparator to reverse the default natural order from the lowest to the highest. Comparator. comparingDouble () internally uses Double. compare ().
If you need to compare int or long, you can use comparingInt () and comparingLong () respectively ().
5. Sort the list using a custom Comparator
In the previous example, we did not specify any comparator because it was unnecessary, but let's look at an example where we defined our own comparator. Our Movie class has a new field -- "starred" -- which is set using the third constructor parameter. In the example, we want to sort the list so that the top of the list is a movie with stars.
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 futuristic ', rating = 8.5} Movie {starred = false, title = 'pulp fiction ', rating = 8.9}
Of course we can use lambda expressions instead of the Anonymous class, as shown below:
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 latest example, Comparator. comparing () uses the first parameter as a function to extract the key for sorting and uses Comparator as the second parameter. Comparator uses the extracted keys for comparison. star1 and star2 are boolean values, indicating m1.getStarred () and m2.getStarred () respectively ().
6. Sort the list by comparison chain
In the last example, we will add a star-studded movie on the top and sort it 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 );
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 ure ', rating = 8.5}
As you can see, we first sort by star and then by score-both reverse, because we want the highest value and the real first.