Skip to content
Justice Tech School

Sorting and Comparators

Comparable defines natural order and Comparator defines custom orders. Comparator.comparing, thenComparing and reversed build sorts.

Example
import java.util.*;
record P(String n, int a) {}
List<P> p = new ArrayList<>(List.of(new P("Zed", 20), new P("Ada", 30), new P("Bob", 20)));
p.sort(Comparator.comparingInt(P::a).thenComparing(P::n));
System.out.println(p);
p.sort(Comparator.comparing(P::n).reversed());
System.out.println(p.get(0).n());

Result

[P[n=Bob, a=20], P[n=Zed, a=20], P[n=Ada, a=30]]
Zed

Exercise

Then sort by a second key.

.(P::n)

Quiz Test

Which sorts a list in place?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.