Java Stream Sort

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 176 of 306

The sorted Operation

sorted returns a stream with the elements in order. It comes in two forms:

Stream<T> sorted()                                // natural order (elements must be Comparable)
Stream<T> sorted(Comparator<? super T> comparator) // order defined by a Comparator
  • Natural order is defined by the class itself through Comparable: numbers ascending, strings in Unicode order, dates chronologically, enums in declaration order.
  • A Comparator defines any other order: descending, by a field, by several fields, case-insensitive, with nulls first.
  • sorted is an intermediate, stateful operation: it must receive every element before it can output the first one (Stream API lesson). It can't be used on infinite streams.
  • Sorting is stable for ordered streams: elements that compare as equal keep their original relative order.
  • The source isn't modified. To sort a list in place, use list.sort(comparator).

Natural Order

import java.util.*;
import java.util.stream.*;

public class S1 {
    record Student(String name, String city, int score) { }

    public static void main(String[] args) {
        System.out.println(Stream.of(42, 7, 99, 13).sorted().toList());
        System.out.println(Stream.of("banana", "apple", "Cherry").sorted().toList());
        System.out.println(Stream.of("banana", "apple", "Cherry").sorted(String.CASE_INSENSITIVE_ORDER).toList());
        System.out.println(Stream.of(42, 7, 99, 13).sorted(Comparator.reverseOrder()).toList());

        List<Student> students = List.of(new Student("Ravi", "Madurai", 78), new Student("Asha", "Chennai", 91));
        try {
            students.stream().sorted().toList();
        } catch (ClassCastException e) {
            System.out.println("ClassCastException: Student is not Comparable");
        }
    }
}

Output:

[7, 13, 42, 99]
[Cherry, apple, banana]
[apple, banana, Cherry]
[99, 42, 13, 7]
ClassCastException: Student is not Comparable
  • Strings sort by character code, so all uppercase letters come before all lowercase ones: Cherry before apple. String.CASE_INSENSITIVE_ORDER ignores case.
  • Comparator.reverseOrder() reverses natural order.
  • sorted() on non-Comparable objects compiles (the compiler can't check it) but throws ClassCastException at runtime. Either implement Comparable (Generic Interfaces lesson) or pass a Comparator.

Building Comparators

The Comparator interface has static factory methods and default methods that build comparators from key extractors — functions that pick the value to compare — so you rarely need to write compare by hand.

import java.util.*;

public class S2 {
    record Student(String name, String city, int score) { }

    public static void main(String[] args) {
        List<Student> s = List.of(
            new Student("Ravi", "Madurai", 78), new Student("Asha", "Chennai", 91),
            new Student("Meena", "Chennai", 78), new Student("Kumar", "Salem", 91),
            new Student("Divya", "Madurai", 65));

        print("by name", s.stream().sorted(Comparator.comparing(Student::name)).toList());
        print("by score", s.stream().sorted(Comparator.comparingInt(Student::score)).toList());
        print("score desc", s.stream().sorted(Comparator.comparingInt(Student::score).reversed()).toList());
        print("score desc, name", s.stream()
            .sorted(Comparator.comparingInt(Student::score).reversed().thenComparing(Student::name)).toList());
        print("city, then score desc", s.stream()
            .sorted(Comparator.comparing(Student::city)
                .thenComparing(Comparator.comparingInt(Student::score).reversed())).toList());
        print("PITFALL reversed() last", s.stream()
            .sorted(Comparator.comparing(Student::city).thenComparingInt(Student::score).reversed()).toList());
        print("name length, then name", s.stream()
            .sorted(Comparator.comparing(Student::name, Comparator.comparingInt(String::length)).thenComparing(Student::name)).toList());
    }

    static void print(String label, List<Student> list) {
        System.out.printf("%-24s %s%n", label + ":", list.stream().map(x -> x.name() + "(" + x.city().charAt(0) + x.score() + ")").toList());
    }
}

Output (each student is shown as name, first letter of the city and score):

by name:                 [Asha(C91), Divya(M65), Kumar(S91), Meena(C78), Ravi(M78)]
by score:                [Divya(M65), Ravi(M78), Meena(C78), Asha(C91), Kumar(S91)]
score desc:              [Asha(C91), Kumar(S91), Ravi(M78), Meena(C78), Divya(M65)]
score desc, name:        [Asha(C91), Kumar(S91), Meena(C78), Ravi(M78), Divya(M65)]
city, then score desc:   [Asha(C91), Meena(C78), Ravi(M78), Divya(M65), Kumar(S91)]
PITFALL reversed() last: [Kumar(S91), Ravi(M78), Divya(M65), Asha(C91), Meena(C78)]
name length, then name:  [Asha(C91), Ravi(M78), Divya(M65), Kumar(S91), Meena(C78)]
MethodMeaning
Comparator.comparing(keyExtractor)Compare by a key that is itself Comparable (Student::name)
Comparator.comparing(keyExtractor, keyComparator)Compare by a key using a specific comparator for the key
comparingInt / comparingLong / comparingDoubleSame for primitive keys, without boxing
cmp.reversed()The reverse of the whole comparator cmp
cmp.thenComparing(...), thenComparingInt(...)Tie-breaker used only when cmp says two elements are equal
Comparator.naturalOrder(), Comparator.reverseOrder()Natural order and its reverse
Comparator.nullsFirst(cmp), nullsLast(cmp)Handle null values safely

Things to notice in the output:

  • Ties keep their original order (stability): in "by score", Ravi and Meena both have 78, and Ravi came first in the source, so he stays first.
  • Tie-breakers make the order fully defined: "score desc, name" puts Meena before Ravi. Without a final tie-breaker, the order of equal elements depends on the input, which can make test results and paging inconsistent.
  • Mixed directions: "city ascending, then score descending" is written by reversing only the score comparator inside thenComparing.
  • The reversed() pitfall: in comparing(city).thenComparingInt(score).reversed(), reversed() applies to the entire chain built so far, so both city and score are reversed (Salem first). Always attach reversed() to the specific comparator you want reversed.
  • A key with its own comparator: comparing(Student::name, comparingInt(String::length)) compares names by length, with alphabetical order as the tie-breaker.

Locale-Aware Ordering and Null Values

import java.text.Collator;
import java.util.*;

public class S3 {
    record Contact(String name, String phone) { }

    public static void main(String[] args) {
        List<Contact> contacts = Arrays.asList(new Contact("Zoe", null), new Contact("asha", "+91-1"),
                                               new Contact("Émile", "+33-2"), new Contact("Bala", "+91-3"));
        System.out.println(contacts.stream().map(Contact::name).sorted().toList());
        Collator collator = Collator.getInstance(Locale.ENGLISH);
        System.out.println(contacts.stream().map(Contact::name).sorted(collator).toList());

        System.out.println(contacts.stream()
            .sorted(Comparator.comparing(Contact::phone, Comparator.nullsLast(Comparator.naturalOrder())))
            .map(Contact::name).toList());
        try {
            contacts.stream().sorted(Comparator.comparing(Contact::phone)).toList();
        } catch (NullPointerException e) {
            System.out.println("without nullsLast: NullPointerException");
        }
    }
}

Output:

[Bala, Zoe, asha, Émile]
[asha, Bala, Émile, Zoe]
[Émile, asha, Bala, Zoe]
without nullsLast: NullPointerException
  • Natural string order isn't alphabetical for people: lowercase names come after uppercase ones, and accented letters (É) come after z. A Collator sorts according to the language's rules — case and accents are treated the way a dictionary would. Use it for any list shown to users (names, cities, product titles). Collator implements Comparator<Object>, so it can be passed to sorted directly.
  • null keys crash a plain comparator: Zoe has no phone number, and comparing(Contact::phone) throws NullPointerException. Wrapping the key comparator in Comparator.nullsLast(...) (or nullsFirst) places null values at the end instead.

Top-N, Minimum and Maximum

import java.util.*;
import java.util.stream.*;

public class TopN {
    public static void main(String[] args) {
        Map<String, Integer> sales = Map.of("Java", 128, "Django", 96, "Docker", 140, "Python", 210, "JS", 96);
        List<String> top3 = sales.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
            .limit(3)
            .map(e -> e.getKey() + "=" + e.getValue())
            .toList();
        System.out.println("top 3: " + top3);
        System.out.println("max: " + Collections.max(sales.entrySet(), Map.Entry.comparingByValue()).getKey());
        System.out.println("min by stream: " + sales.entrySet().stream().min(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElse("-"));

        List<String> stable = Stream.of("b1", "a1", "b2", "a2", "b3")
            .sorted(Comparator.comparing(s -> s.charAt(0))).toList();
        System.out.println("stable: " + stable);
    }
}

Output:

top 3: [Python=210, Docker=140, Java=128]
max: Python
min by stream: Django
stable: [a1, a2, b1, b2, b3]
  • Sorting a map by value: stream its entrySet() and use Map.Entry.comparingByValue() / comparingByKey(). The explicit type witness Map.Entry.<String, Integer>comparingByValue() is needed because .reversed() is called on the result before the compiler knows the target type.
  • Top N is sorted(...).limit(n).
  • For just the single largest or smallest element, don't sort: max(comparator) and min(comparator) find it in one pass (sorting does far more work). Django and JS both have 96; min returns one of them.
  • Stability: sorting by the first character only keeps a1 before a2 and b1, b2, b3 in their original order.

Practical Example: Sort Options for a Product Listing

An online shop lets users choose how products are sorted — price low to high, price high to low, top rated, most popular, name. Sold-out items should always appear last, and every option needs a final tie-breaker so the order (and therefore the pages) never changes between requests. A map from sort keys to comparators makes each option a single entry.

import java.util.*;
import java.util.stream.*;

public class Listing {
    record Product(String name, double price, double rating, int reviews, int soldLastWeek, boolean inStock) { }

    static final Map<String, Comparator<Product>> SORTS = Map.of(
        "price_asc", Comparator.comparingDouble(Product::price),
        "price_desc", Comparator.comparingDouble(Product::price).reversed(),
        "rating", Comparator.comparingDouble(Product::rating).reversed()
                            .thenComparing(Comparator.comparingInt(Product::reviews).reversed()),
        "popular", Comparator.comparingInt(Product::soldLastWeek).reversed(),
        "name", Comparator.comparing(Product::name, String.CASE_INSENSITIVE_ORDER));

    static List<String> list(List<Product> products, String sortKey, int page, int size) {
        Comparator<Product> chosen = SORTS.getOrDefault(sortKey, SORTS.get("popular"));
        Comparator<Product> full = Comparator.comparing(Product::inStock).reversed()
            .thenComparing(chosen)
            .thenComparing(Product::name);
        return products.stream()
            .sorted(full)
            .skip((long) (page - 1) * size)
            .limit(size)
            .map(p -> String.format("%s(%.0f, %.1f*%s)", p.name(), p.price(), p.rating(), p.inStock() ? "" : ", sold out"))
            .toList();
    }

    public static void main(String[] args) {
        List<Product> bags = List.of(
            new Product("Trek Backpack", 1899, 4.6, 320, 41, true),
            new Product("city sling", 799, 4.2, 88, 65, true),
            new Product("Laptop Bag Pro", 2499, 4.8, 120, 22, false),
            new Product("Daypack", 1299, 4.6, 510, 37, true),
            new Product("Gym Duffel", 999, 4.0, 45, 12, true));

        for (String key : List.of("price_asc", "price_desc", "rating", "popular", "name", "unknown")) {
            System.out.printf("%-10s %s%n", key, list(bags, key, 1, 5));
        }
        System.out.printf("%-10s %s%n", "page 2", list(bags, "price_asc", 2, 2));
    }
}

Output:

price_asc  [city sling(799, 4.2*), Gym Duffel(999, 4.0*), Daypack(1299, 4.6*), Trek Backpack(1899, 4.6*), Laptop Bag Pro(2499, 4.8*, sold out)]
price_desc [Trek Backpack(1899, 4.6*), Daypack(1299, 4.6*), Gym Duffel(999, 4.0*), city sling(799, 4.2*), Laptop Bag Pro(2499, 4.8*, sold out)]
rating     [Daypack(1299, 4.6*), Trek Backpack(1899, 4.6*), city sling(799, 4.2*), Gym Duffel(999, 4.0*), Laptop Bag Pro(2499, 4.8*, sold out)]
popular    [city sling(799, 4.2*), Trek Backpack(1899, 4.6*), Daypack(1299, 4.6*), Gym Duffel(999, 4.0*), Laptop Bag Pro(2499, 4.8*, sold out)]
name       [city sling(799, 4.2*), Daypack(1299, 4.6*), Gym Duffel(999, 4.0*), Trek Backpack(1899, 4.6*), Laptop Bag Pro(2499, 4.8*, sold out)]
unknown    [city sling(799, 4.2*), Trek Backpack(1899, 4.6*), Daypack(1299, 4.6*), Gym Duffel(999, 4.0*), Laptop Bag Pro(2499, 4.8*, sold out)]
page 2     [Daypack(1299, 4.6*), Trek Backpack(1899, 4.6*)]

How it works:

  1. A table of comparators. Each sort option is a comparator stored under the key the web page sends (?sort=price_desc). Adding an option is one map entry. Unknown keys fall back to "popular" with getOrDefault, so a tampered URL can't cause an error.
  2. Rating with a tie-breaker: Daypack and Trek Backpack both have 4.6; the one with more reviews (Daypack, 510) comes first.
  3. Wrapping every option: the final comparator puts in-stock products first, then applies the chosen option, then the product name as the last tie-breaker. comparing(Product::inStock) orders false before true, so .reversed() puts in-stock items first; the Laptop Bag Pro is last in every listing even though it's the best rated.
  4. Case-insensitive names: "city sling" sorts with the other names instead of after all capitalised ones.
  5. Paging after sorting: skip and limit select a page from the fully sorted list. Because the order is completely defined by the tie-breakers, page 2 always continues exactly where page 1 ended.

For data in a database, the same sort options translate into ORDER BY clauses so the database sorts and pages; the comparator table is the in-memory equivalent, used for cached catalogues, search results and data already loaded.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Sort and get answers drawn from it.

Signed-in readers only.