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.
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.
Stream<T> distinct()
This method has no parameters.
The method returns a new stream of distinct elements.
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);}}
Supplier
to generate a stream of strings.distinct
method on the stream and print the stream.