Table of Contents
StringList" >Sort alphabeticallyStringList
integerSort list" >Sort integerSort list
Sort list by string field
Sort the list by double field
Sort the list using a custom comparator
Sort the list with a comparison chain
Home Java javaTutorial Java8 comparator-detailed explanation of how to sort List

Java8 comparator-detailed explanation of how to sort List

Mar 18, 2017 am 11:11 AM

Java8 Comparator - Detailed explanation of how to sort a List

In this article, we will see a few details on how to sort a List in Java 8 example of.

Sort alphabeticallyStringList

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]
Copy after login

London's "L" uses lowercase letters to better highlight Comparator.naturalOrder() (returns sorting uppercase first The difference between a comparator for letters) and String.CASE_INSENSITIVE_ORDER (a comparator that returns case-insensitive).

Basically, in Java 7, we used Collection.sort() which accepts a List and finally a Comparator - in Java 8, we have the new List.sort() which accepts a Comparator.

Sort integerSort 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]
Copy after login

Sort list by string field

Suppose we have a Movie class, and we want to "by title title" "Sort the List. We can use Comparator.comparing() , passing a function that extracts the field used to sort title - in this case.

List<Movie> movies = Arrays.asList(
        new Movie("Lord of the rings"),
        new Movie("Back to the future"),
        new Movie("Carlito&#39;s way"),
        new Movie("Pulp fiction"));
movies.sort(Comparator.comparing(Movie::getTitle));
movies.forEach(System.out::println);
Copy after login

Output:

Movie{title=&#39;Back to the future&#39;}
Movie{title=&#39;Carlito&#39;s way&#39;}
Movie{title=&#39;Lord of the rings&#39;}
Movie{title=&#39;Pulp fiction&#39;}
Copy after login

Maybe you will notice that we are not passing any Comparator, but the List is sorted correctly. This is because title - the extracted field - is a string, and strings implement the Comparable interface . If you look at the Comparator.comparing() implementation, you'll see that it calls compareTo on the extracted key.

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

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 a list of Movies from 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&#39;s way", 7.9),
        new Movie("Pulp fiction", 8.9));
movies.sort(Comparator.comparingDouble(Movie::getRating)
                      .reversed());
movies.forEach(System.out::println);
Copy after login

We use the reversed function on the Comparator in order to reverse the default natural order from lowest to highest. Comparator.comparingDouble() uses Double.compare() internally.

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

Sort the list using a custom comparator

In the previous example, we did not specify any comparator because it was not necessary, but let us look at an example in which we defined 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 the starred movies are 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&#39;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);
Copy after login

The result will be:

Movie{starred=true, title=&#39;Lord of the rings&#39;, rating=8.8}
Movie{starred=true, title=&#39;Carlito&#39;s way&#39;, rating=7.9}
Movie{starred=false, title=&#39;Back to the future&#39;, rating=8.5}
Movie{starred=false, title=&#39;Pulp fiction&#39;, rating=8.9}
Copy after login

We can of course use lambdaexpression instead of the Anonymous class as follows:

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

We can also Using Comparator.comparing() again:

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

In the latest example, Comparator.comparing() takes the first argument as a function that extracts the key used for sorting, and the Comparator as the second argument. Comparator uses extracted keys for comparison, star1 and star2 are really boolean values, representing m1.getStarred() and m2.getStarred() respectively.

Sort the list with a comparison chain

In the last example, we want to add the starred movies 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&#39;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);
Copy after login

The output is:

Movie{starred=true, title=&#39;Lord of the rings&#39;, rating=8.8}
Movie{starred=true, title=&#39;Carlito&#39;s way&#39;, rating=7.9}
Movie{starred=false, title=&#39;Pulp fiction&#39;, rating=8.9}
Movie{starred=false, title=&#39;Back to the future&#39;, rating=8.5}
Copy after login

As you can see, we sort by stars first and then by rating - both are reversed because we want the highest value and a true first.

The above is the detailed content of Java8 comparator-detailed explanation of how to sort List. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

How to sort content in a Microsoft Word table How to sort content in a Microsoft Word table Apr 17, 2023 pm 02:49 PM

When it comes to Microsoft Excel, tables are the most common. Therefore, everyone knows very well how to sort data within a table in Microsoft Excel. But tables are rare when it comes to Word, and the need to sort data in tables in Word is even rarer. But sure, you may need to have a table in a Word document, and sometimes you may even need to sort the data in it. One way to sort data in a Word table is to import the data into Excel, sort it from Excel, and then bring the sorted table back to Word. Well, don’t even think about resorting to this! When Word itself has a pair of tables

How to calculate date one week later using Java 8? How to calculate date one week later using Java 8? Apr 21, 2023 pm 11:01 PM

How to calculate the date one week later in Java8 This example will calculate the date one week later. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values ​​after returning. packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

Java program to search user defined object from list by using binary search comparator Java program to search user defined object from list by using binary search comparator Aug 28, 2023 pm 04:05 PM

Java comparator interface for sorting Java objects. The comparator class in Java compares different objects (Obj01, Obj02) by calling "java.util.comparator". In this method, objects can be compared based on the return value. The comparison can be positive, equal, or negative. This process provides the user with multiple sorting sequences. There are many ways to compare the two methods. publicintcompareclass(obj1,obj2) - performs a comparison between two objects. publicBooleanequals(obj)-Compares the current object with the specified object. Java collection class - provides access to elements in a data collection

How to use the Clock class in Java8 How to use the Clock class in Java8 Apr 25, 2023 pm 03:37 PM

Java8's Clock class Java8 adds a Clock class for obtaining the current timestamp, or date and time information in the current time zone. Where System.currentTimeInMillis() and TimeZone.getDefault() were used before, they can be replaced by Clock. packagecom.shxt.demo02;importjava.time.Clock;publicclassDemo10{publicstaticvoidmain(String[]args){//Returnsthecurrenttimebase

How to deal with time zones in Java8 How to deal with time zones in Java8 Apr 27, 2023 pm 09:22 PM

Handling time zones in Java 8 Java 8 not only separates date and time, but also separates time zones. There are now a series of separate classes such as ZoneId to handle specific time zones and ZoneDateTime to represent time in a certain time zone. This was done by the GregorianCalendar class before Java8. The following example shows how to convert the time in this time zone to the time in another time zone. packagecom.shxt.demo02;importjava.time.LocalDateTime;importjava.time.ZoneId;importjava.time.ZonedDateT

Sort Java vectors in descending order using comparator Sort Java vectors in descending order using comparator Aug 20, 2023 pm 07:17 PM

Vectors implement the List interface for creating dynamic arrays. Arrays whose size is not fixed and can grow as per our requirement are called dynamic arrays. Comparator is an interface available in the ‘java.util’ package. Sorting means rearranging the elements of a given list or array in ascending or descending order. In this article, we will create a vector and then try to sort its elements in descending order using a comparator. Program to sort Java vectors in descending order Comparator As its name suggests, it is used to compare something. In Java, Comparator is an interface for sorting custom objects. We can write in its built-in method "compare()"

What are the date comparison methods in Java8? What are the date comparison methods in Java8? Apr 29, 2023 pm 04:46 PM

Java8 Date Comparison Methods In Java8, you can use the new isBefore(), isAfter(), isEqual() and compareTo() to compare LocalDate, LocalTime and LocalDateTime. The following example to compare two java.time.LocalDate@TestvoidtestDateCompare4() throwsParseException{DateTimeFormattersdf=DateTimeFormatter.ofPattern("yyyy-MM-dd&quot

See all articles