Stream.distinct()
Removes duplicate elements from a stream.
Available since: Java 8
Syntax
Stream<T> distinct()Return value
Stream<T>A stream without duplicates.
Examples
Unique values in the original order:
void main() {
List<Integer> unique = List.of(3, 1, 3, 2, 1).stream().distinct().toList();
IO.println(unique);
}Output:
[3, 1, 2]Notes
Duplicates are detected with equals() and hashCode(). For ordered streams the first occurrence of each value is kept. Without streams new LinkedHashSet<>(list) does the same.
See also
- Set.copyOf() — Creates an unmodifiable set from a collection, dropping duplicates.
- LinkedHashSet — A set that remembers the insertion order of elements.
- Stream.sorted() — Sorts the elements of a stream.
Related recipes
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.