Java Stream distinct() Method Tutorial

In this section we will learn what the Stream distinct() method is and how to use it in Java.

What is Java Stream distinct() Method?

The Java Stream distinct() method is used to clear a stream from duplicated elements.

For example, if in a stream there’s the value 4 repeated multiple times, calling this method will remove all the duplicated elements and only let one copy of this value to pass.

Note: this method is intermediate and lazy.

Java distinct() Method Syntax:

Stream<T> distinct()

distinct() Method Parameters:

The method does not take an argument.

distinct() Method Return Value:

The return value of this method is a new stream with no duplicated element.

distinct() Method Exceptions:

The method does not throw an exception.

Example: using Stream distinct() method

class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,7,86,54,5);
        stream.distinct().forEach(e->System.out.print(e+", "));


1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 423, 34, 56, 86, 54,

Top Technologies