Java Reference ยท Streams and Functional
Java Stream distinct() and sorted()
Reference for Java Stream.distinct() and sorted(): remove duplicates with equals(), sort by natural or custom order, stability and memory costs.
distinct() removes duplicate elements, using equals() (and hashCode()) to decide what a duplicate is. sorted() orders the elements, either by their natural order (Comparable) or with a Comparator you pass in.
Both are stateful intermediate operations: they cannot emit anything until they have seen (some or all of) the input. sorted() must read every element before it can pass the first one downstream.
List<String> tidy = words.stream().distinct().sorted().toList();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Stream<T> distinct() Stream<T> sorted() Stream<T> sorted(Comparator<? super T> comparator)
| Name | Description |
|---|---|
comparator |
Defines the order. Without it the elements must implement Comparable. |
Returns: a stream of unique or sorted elements. Throws: ClassCastException (when the terminal operation runs) if elements are not Comparable and no comparator was given.
Usage notes
distinct()usesequals(), so your classes need a correctequals/hashCodepair. Records provide one automatically.- First wins: for an ordered stream
distinct()keeps the first occurrence of each value and keeps order; on an unordered or parallel stream any occurrence may be kept. - Memory:
distinct()remembers every element it has seen,sorted()buffers the whole stream. Do not apply them to unbounded streams without alimitthat comes earlier. - Stability:
sorted()is stable on ordered streams, so equal elements keep their original relative order. - Order of operations matters for cost:
filterbeforesortedsorts less data;limitaftersortedstill needs all input sorted first. - Distinct by key: there is no
distinctBy. Use atoMapmerge function as above, or track keys in a set in an ordered, sequential pipeline. - Top N:
sorted(...).limit(n)is simple; for big data aPriorityQueueavoids sorting everything. - Nulls break natural-order sorting (
NullPointerException); useComparator.nullsFirst(...).