Streams: Stream.sorted() without a comparator requires Comparable elements

The no-argument sorted() calls each element's own compareTo, so it works for naturally ordered types like Integer but throws ClassCastException on a type such as a record that never implemented Comparable.

Code
record Point(int x, int y) {}
List<Integer> nums = new ArrayList<>(List.of(5, 3, 4, 1));
System.out.println("Sorted ints: " + nums.stream().sorted().toList());
List<Point> points = List.of(new Point(2, 1), new Point(1, 1));
try {
    points.stream().sorted().toList();
} catch (ClassCastException e) {
    System.out.println("Sorting non-Comparable records throws: " + e.getClass().getSimpleName());
}
Output
Sorted ints: [1, 3, 4, 5]
Sorting non-Comparable records throws: ClassCastException
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms