distinct() keeps only the first element for each distinct equals/hashCode value, so records with the same field values collapse into one even though they are separate objects.
record Point(int x, int y) {}
List<Point> points = List.of(new Point(1, 1), new Point(1, 1), new Point(2, 2));
List<Point> distinctPoints = points.stream().distinct().toList();
System.out.println("Distinct records (equals-based): " + distinctPoints);
List<String> letters = List.of(new String("x"), new String("x"));
long distinctStrings = letters.stream().distinct().count();
System.out.println("Distinct strings by value: " + distinctStrings);
Distinct records (equals-based): [Point[x=1, y=1], Point[x=2, y=2]]
Distinct strings by value: 1
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