Java Stream Sort
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
Comparatordefines any other order: descending, by a field, by several fields, case-insensitive, withnulls first. sortedis 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:
Cherrybeforeapple.String.CASE_INSENSITIVE_ORDERignores case. Comparator.reverseOrder()reverses natural order.sorted()on non-Comparableobjects compiles (the compiler can't check it) but throwsClassCastExceptionat runtime. Either implementComparable(Generic Interfaces lesson) or pass aComparator.
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)]
| Method | Meaning |
|---|---|
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 / comparingDouble | Same 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: incomparing(city).thenComparingInt(score).reversed(),reversed()applies to the entire chain built so far, so both city and score are reversed (Salem first). Always attachreversed()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 afterz. ACollatorsorts 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).CollatorimplementsComparator<Object>, so it can be passed tosorteddirectly. nullkeys crash a plain comparator: Zoe has no phone number, andcomparing(Contact::phone)throwsNullPointerException. Wrapping the key comparator inComparator.nullsLast(...)(ornullsFirst) placesnullvalues 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 useMap.Entry.comparingByValue()/comparingByKey(). The explicit type witnessMap.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)andmin(comparator)find it in one pass (sorting does far more work). Django and JS both have 96;minreturns one of them. - Stability: sorting by the first character only keeps
a1beforea2andb1,b2,b3in 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:
- 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" withgetOrDefault, so a tampered URL can't cause an error. - Rating with a tie-breaker: Daypack and Trek Backpack both have 4.6; the one with more reviews (Daypack, 510) comes first.
- 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)ordersfalsebeforetrue, so.reversed()puts in-stock items first; the Laptop Bag Pro is last in every listing even though it's the best rated. - Case-insensitive names: "city sling" sorts with the other names instead of after all capitalised ones.
- Paging after sorting:
skipandlimitselect 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.