distinct and sorted
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)distinct removes repeated elements and sorted puts elements in order. Both are intermediate operations, but unlike filter and map they must remember other elements to do their job.
distinct removes duplicates with equals and hashCode
distinct is an intermediate step that removes repeated elements, keeping the first copy of each in its original order. It decides what a repeat is with equals and hashCode.
Duplicates creep in everywhere: a student registers twice, two orders contain the same item, a log repeats the same error. The old way is a LinkedHashSet loop: add every element and let the set reject repeats. distinct() does the same inside a pipeline.
Example 1 · distinct versus a LinkedHashSet loop
import java.util.LinkedHashSet;import java.util.List;import java.util.Set;
public class DistinctDemo { public static void main(String[] args) { List<String> registrations = List.of("Asha", "Ravi", "Asha", "Meena", "Ravi", "Kiran");
Set<String> seen = new LinkedHashSet<>(); for (String name : registrations) { seen.add(name); } System.out.println("Loop: " + seen);
List<String> unique = registrations.stream() .distinct() .toList(); System.out.println("distinct: " + unique);
List<Integer> scores = List.of(4, 6, 4, 1, 6, 6); System.out.println("Scores: " + scores.stream().distinct().toList()); }}Loop: [Asha, Ravi, Meena, Kiran] distinct: [Asha, Ravi, Meena, Kiran] Scores: [4, 6, 1]
What this code does
distinctkeeps the first copy of each value and keeps the original order, just like aLinkedHashSet.- It works for any type with a proper
equalsandhashCode, such asStringandInteger.
Example 2 · Records work with distinct; a plain class does not
import java.util.List;
record StudentRec(String name, int marks) {}
class StudentPlain { String name; int marks;
StudentPlain(String name, int marks) { this.name = name; this.marks = marks; }}
public class DistinctRecordDemo { public static void main(String[] args) { List<StudentRec> recs = List.of( new StudentRec("Asha", 78), new StudentRec("Asha", 78), new StudentRec("Asha", 81)); System.out.println("Records: " + recs.stream().distinct().count()); System.out.println(recs.stream().distinct().toList());
List<StudentPlain> plain = List.of( new StudentPlain("Asha", 78), new StudentPlain("Asha", 78), new StudentPlain("Asha", 81)); System.out.println("Plain class: " + plain.stream().distinct().count()); }}Records: 2 [StudentRec[name=Asha, marks=78], StudentRec[name=Asha, marks=81]] Plain class: 3
What this code does
- A record builds
equalsandhashCodefrom all its fields, so the twoAsha 78records are equal and one is dropped.Asha 81differs in marks, so it stays. StudentPlaindoes not overrideequals, so every object is equal only to itself anddistinctremoves nothing.
To decide that two elements are the same, distinct uses equals and hashCode, exactly like a HashSet. It keeps the first time it sees an element and drops later copies, and the survivors stay in their original order. Records get equals and hashCode for free, built from all their fields, so distinct works on them out of the box. A plain class that does not override equals is compared by identity: two objects with the same name and marks still count as different, and nothing is removed.
distinct seems to do nothing on your own class, check that the class overrides both equals and hashCode, or turn it into a record.sorted: natural order or a Comparator
sorted is an intermediate step that puts the elements in order, either their natural order or the order of a Comparator that you give it.
sorted() with no argument uses the natural order, the order a class defines with Comparable: numbers small to large, Strings A to Z (capitals before small letters). The source list is not changed; only the stream is sorted.
Example 3 · sorted in natural order and with a Comparator
import java.util.Comparator;import java.util.List;
public class SortedDemo { public static void main(String[] args) { List<String> cities = List.of("pune", "Delhi", "Agra", "chennai", "Goa");
System.out.println("Natural: " + cities.stream().sorted().toList()); System.out.println("Ignore case: " + cities.stream() .sorted(String.CASE_INSENSITIVE_ORDER).toList()); System.out.println("By length: " + cities.stream() .sorted(Comparator.comparing(String::length)).toList());
List<Integer> marks = List.of(64, 98, 71, 98, 55); System.out.println("High to low: " + marks.stream() .sorted(Comparator.reverseOrder()).toList()); System.out.println("Unique, high to low: " + marks.stream() .distinct() .sorted(Comparator.reverseOrder()) .toList()); System.out.println("Source: " + marks); }}Natural: [Agra, Delhi, Goa, chennai, pune] Ignore case: [Agra, chennai, Delhi, Goa, pune] By length: [Goa, pune, Agra, Delhi, chennai] High to low: [98, 98, 71, 64, 55] Unique, high to low: [98, 71, 64, 55] Source: [64, 98, 71, 98, 55]
What this code does
- Natural order puts capital letters before small ones, so
puneandchennaicome last.CASE_INSENSITIVE_ORDERfixes that.puneandAgratie on length and keep their original order, because the sort is stable. distinctandsortedcombine well: remove the repeated 98, then sort. The source list never changes.
sorted(comparator) uses any order you like. All the comparators from the Collections section work here: Comparator.reverseOrder(), String.CASE_INSENSITIVE_ORDER, Comparator.comparing(Student::name). Calling sorted() on a class that is not Comparable compiles but fails at run time with a ClassCastException, because Java cannot find a natural order. Give such classes a comparator.
comparing, thenComparing and reversed in a pipeline
A leaderboard sorts by marks, highest first, and breaks ties by name. In a pipeline that reads .sorted(Comparator.comparing(Student::marks).reversed().thenComparing(Student::name)).
Example 4 · A leaderboard: comparing, reversed and thenComparing
import java.util.Comparator;import java.util.List;
record Student(String name, int marks) {}
public class LeaderboardDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Ravi", 88), new Student("Asha", 92), new Student("Kiran", 88), new Student("Meena", 75), new Student("Arjun", 92));
System.out.println("Marks high to low, ties by name A to Z:"); students.stream() .sorted(Comparator.comparing(Student::marks).reversed() .thenComparing(Student::name)) .forEach(s -> System.out.println(" " + s.marks() + " " + s.name()));
System.out.println("reversed() at the end flips the names too:"); students.stream() .sorted(Comparator.comparing(Student::marks) .thenComparing(Student::name) .reversed()) .forEach(s -> System.out.println(" " + s.marks() + " " + s.name())); }}Marks high to low, ties by name A to Z: 92 Arjun 92 Asha 88 Kiran 88 Ravi 75 Meena reversed() at the end flips the names too: 92 Asha 92 Arjun 88 Ravi 88 Kiran 75 Meena
What this code does
reversed()placed right after the marks key reverses only that key.thenComparing(Student::name)then breaks ties A to Z: Arjun before Asha, Kiran before Ravi.- In the second pipeline
reversed()comes last and flips the whole comparator, so the ties come out Z to A.Comparator.comparing(Student::marks, Comparator.reverseOrder())is another clear way to reverse one key only.
Watch where reversed() sits. It reverses everything built so far. Placed after thenComparing, it would flip the names too, so ties come out Z to A. Put it right after the key you want reversed, or pass the order for that key alone: Comparator.comparing(Student::marks, Comparator.reverseOrder()). A stable sort keeps equal elements in their original order. Stream sorted is stable on ordered streams such as lists, so a tie-breaker is needed only when the original order is not good enough.
Stateful steps: why sorted needs every element first
filter and map are stateless: they pass each element on at once. A stateful step must remember other elements: distinct remembers what it has passed, and sorted waits for every element.
Example 5 · Stateful: sorted waits for every element
import java.util.List;
public class StatefulTraceDemo { public static void main(String[] args) { List<Integer> marks = List.of(70, 40, 90);
System.out.println("Without sorted:"); marks.stream() .filter(m -> { System.out.println(" filter " + m); return true; }) .forEach(m -> System.out.println(" print " + m));
System.out.println("With sorted:"); marks.stream() .filter(m -> { System.out.println(" filter " + m); return true; }) .sorted() .forEach(m -> System.out.println(" print " + m)); }}Without sorted: filter 70 print 70 filter 40 print 40 filter 90 print 90 With sorted: filter 70 filter 40 filter 90 print 40 print 70 print 90
What this code does
- Without
sorted, each element goes all the way toforEachbefore the next one starts: filter, print, filter, print. - With
sorted, all three elements pass the filter first. Only whensortedhas seen everything does it release them, smallest first. The print infilteris only for tracing; thepeeklesson shows the proper debugging tool.
So sorted breaks the usual one-at-a-time flow: every element runs through the steps before it, sorted collects them all, and only then the sorted elements flow through the later steps.
That costs memory for large data and never finishes on an endless stream. Put filter before sorted so it sorts fewer elements.
Trap: reversed() after a lambda comparator
Java works out a lambda's parameter type from where the lambda is used. In .sorted(Comparator.comparing(s -> s.marks())) the target is sorted, so s is a Student.
Example 6 · Trap: reversed() loses the lambda type
import java.util.Comparator;import java.util.List;
record Student(String name, int marks) {}
public class ReversedTrapDemo { public static void main(String[] args) { List<Student> students = List.of(new Student("Asha", 78), new Student("Ravi", 91)); List<Student> ranked = students.stream() .sorted(Comparator.comparing(s -> s.marks()).reversed()) .toList(); System.out.println(ranked); }}ReversedTrapDemo.java:10: error: cannot find symbol
.sorted(Comparator.comparing(s -> s.marks()).reversed())
^
symbol: method marks()
location: variable s of type Object
1 errorWhat this code does
- The lambda is now inside
comparing(...), whose result goes to.reversed(), not tosorted. Java cannot see thatsis aStudentand treats it as anObject, which has nomarks(). - Write
Comparator.comparing(Student::marks).reversed()orComparator.comparing((Student s) -> s.marks()).reversed(). Both tell Java the type.
Add .reversed() and the lambda is no longer the direct argument of sorted. Java has to type comparing(...) alone, finds no clue, and makes s an Object. The error is "cannot find symbol ... variable s of type Object". Fix it with a method reference, Comparator.comparing(Student::marks).reversed(), or a typed lambda, (Student s) -> s.marks().
Fix the error
Fix the reversed comparator
Read the real compiler error, then pick the line that fixes it.
Sort the names from the longest to the shortest.
Error
SortFix.java:8: error: cannot find symbol
names.sort(Comparator.comparing(n -> n.length()).reversed());
symbol: method length()
location: variable n of type ObjectNext step
Check your understanding
12 quick questions