Java Stream distinct() Example

The Java Stream distinct() method is an intermediate operation. 

The Java Stream distinct() method is a non-terminal operation that returns a new Stream that will only contain the distinct elements from the original stream. Any duplicates will be eliminated. 

Java Stream distinct() Example

Here is an example of the Java Stream distinct() method:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("one");

        Stream<String> stream = stringList.stream();

        List<String> distinctStrings = stream
                .distinct()
                .collect(Collectors.toList());

        System.out.println(distinctStrings);
    }
}

Output:

[one, two, three]

Java Stream Methods/APIs Examples


Comments