VOOZH about

URL: https://www.geeksforgeeks.org/java/stream-distinct-java/

⇱ Stream.distinct() in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stream.distinct() in Java

Last Updated : 26 Dec, 2025

The distinct() method in Java is used to remove duplicate elements from a stream. It returns a new stream containing only unique elements based on the equals() and hashCode() methods.

  • It is an intermediate operation, meaning it returns a stream and does not produce a final result by itself.
  • For ordered streams, the order of elements is preserved.
  • For unordered streams, the order of distinct elements is not guaranteed.
  • It is a stateful operation because it keeps track of previously seen elements.

Example:


Output
1
2
3

Explanation:

  • stream() converts the list into a stream.
  • distinct() removes duplicate elements using equals() and hashCode().
  • forEach() prints each unique element.

Syntax

Stream<T> distinct()

Example 1: This program demonstrates how to use the Stream.distinct() method in Java to remove duplicate elements from a stream.


Output
Geeks
for
GeeksQuiz
GeeksforGeeks

Explanation:

  • distinct() filters out duplicate strings using equals() and hashCode().
  • forEach(System.out::println) prints each unique element from the stream.

Example 2: This program counts the number of distinct elements in a list using the Stream.distinct() method


Output
4

Explanation: count() returns the total number of unique elements in the stream.

Related Topics:

Comment