Skip to content
Tutorials Center
My learning

Topics

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.

Java
List<String> tidy = words.stream().distinct().sorted().toList();

Try it

Java Duplicates and ordering

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.

Java Distinct by a key, and missing Comparable

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

Java
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() uses equals(), so your classes need a correct equals/hashCode pair. 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 a limit that comes earlier.
  • Stability: sorted() is stable on ordered streams, so equal elements keep their original relative order.
  • Order of operations matters for cost: filter before sorted sorts less data; limit after sorted still needs all input sorted first.
  • Distinct by key: there is no distinctBy. Use a toMap merge function as above, or track keys in a set in an ordered, sequential pipeline.
  • Top N: sorted(...).limit(n) is simple; for big data a PriorityQueue avoids sorting everything.
  • Nulls break natural-order sorting (NullPointerException); use Comparator.nullsFirst(...).