What is the distinct() method of the stream interface in Java?

The distinct() method of the Stream interface returns a stream of distinct elements. We can also use the hashCode() and eqauls() methods to get the distinct elements. However, distinct is a stateful intermediate operation.

  • In ordered streams, the selection of different elements is stable.
  • In unordered streams, the selection of distinct elements is not always stable and can change.

The Stream interface is defined in the java.util.stream package. To import the Stream interface, we use the following import statement:

import java.util.stream.Stream;

The following illustration explains the working of a distinct() method.

working of a distinct() method

Syntax

Stream<T> distinct()

Parameters

This method has no parameters.

Return value

The method returns a new stream of distinct elements.

Code

Run the following code to understand how the distinct() method works:

import java.util.function.Supplier;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
Supplier<Stream<String>> streamSupplier = () -> Stream.of("hello", "educative", "educative");
System.out.println("Stream before distinct operation:");
streamSupplier.get().forEach(System.out::println);
System.out.println("Stream after distinct operation:");
streamSupplier.get().distinct().forEach(System.out::println);
}
}

Explanation

  • Lines 1-2: We import the relevant packages and classes.
  • Line 7: We define a Supplier to generate a stream of strings.
  • Line 11: We print the stream before the distinct operation.
  • Line 15: We apply the distinct method on the stream and print the stream.

Free Resources