search
HomeJavajavaTutorialJava8 comparator-detailed explanation of how to sort List

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]

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]

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);

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;}

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));

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);

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);

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}

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;
});

We can also Using 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 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);

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}

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
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
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft