Java8 comparator, how to sort the List

Source: Internet
Author: User

In this article, we'll look at a couple of examples of how to sort list in Java 8.
I. Sorting strings by Alphabetical list
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]
The "L" in London uses lowercase letters in order to better highlight Comparator.naturalorder () (returns a comparator that first sorts uppercase letters) and String.case_insensitive_order (Returns the difference between case-insensitive comparators).
Basically, in Java 7, we use Collection.sort () to accept the List and the last comparator--in Java 8, and we have a new list.sort () to accept comparator.
two. Sorting the 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]
three. Sort the list by string field
Let's say we have a movie class, and we want to sort the list by title, title. We can use Comparator.comparing () to pass a function that extracts the field used to sort the title-in this case.
list<movie> movies = Arrays.aslist (
New Movie ("Lord of the Rings"),
New Movie ("Back to the Future"),
New Movie ("Carlito's"),
New Movie ("Pulp Fiction"));
Movies.sort (comparator.comparing (movie::gettitle));
Movies.foreach (System.out::p rintln);
Output:
Movie{title= ' Back to the Future '}
Movie{title= ' Carlito ' s-the-movie{title= ' Lord of the Rings '} movie{title= ' Pulp fiction '}
Perhaps you will notice that we did not pass any comparator, but sorted the list correctly. This is because the title--extracted field--is a string, and the string implements a comparable interface. If you look at the comparator.comparing () implementation, you will see it call CompareTo on the extracted key.
Return (comparator<t> & Serializable)
(c1, C2), Keyextractor.apply (C1). CompareTo (keyextractor.apply (C2));
four. Sort the list by double field
In a similar way, we can use comparator.comparingdouble () to compare double values. In the example, we want to order the movie list by the highest-to-lowest rating.
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", 7.9),
New Movie ("Pulp fiction", 8.9));
Movies.sort (comparator.comparingdouble (movie::getrating)
. reversed ());
Movies.foreach (System.out::p rintln);
We use the reversed function on comparator to reverse the default from lowest to highest natural order. Comparator.comparingdouble () uses Double.compare () internally.
If you need to compare int or long, then you can use Comparingint () and Comparinglong () respectively.
Five. Sort the list using a custom comparer
In the previous example, we did not specify any comparators, because there is no need, but let's look at an example where we define our own comparators. Our movie class has a new field--"starred"--using the third constructor parameter setting. In the example, we want to sort the list so that the top of the list is the star-marked movie.
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", 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::p rintln);
The result will be:
Movie{starred=true, title= ' Lord of the Rings ', rating=8.8}
Movie{starred=true, title= ' Carlito ' s-", 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 lambda expressions instead of the 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 latest example, comparator.comparing () takes the first parameter as a function to extract the key used for sorting, and Comparator as the second argument. Comparator uses the extracted keys to compare, Star1 and star2 are really Boolean values, representing M1.getstarred () and m2.getstarred () respectively.
Six. Sort the list with a comparison chain
In the last example, we'll add the star-marked movie to the top and sort by the 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", 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::p rintln);
The output is:
Movie{starred=true, title= ' Lord of the Rings ', rating=8.8}
Movie{starred=true, title= ' Carlito ' s ", 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 can see, we first sort by star and then by rating-both are reversed because we want the highest value and the real first.

Java8 comparator, how to sort the List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.