Java 8 Stream distinct operation will return a stream consisting of the distinct elements of the Stream.
The distinct() operation is an intermediate operation, which means it return a new stream. So distinct() creates a new Stream that contains the elements of the initial stream that match the given predicate.
Stream.distinct() Operation Signature
Let’s take a look at our sample Java code that creates a String collection of array elements, collect the elements into a Stream, request no duplicates with distinct(), and print out the unique elements then stored in another collection.
//Define a Collection of Strings
Collection<String> listStrings = Arrays.asList("Java", "Code", "Depot", "Java", "Samples", "Code", "Tutorials");
//Request Collection with only unique elements from Stream
List<String> uniqueElements = listStrings.stream().distinct().collect(Collectors.toList());
//Print out unique Elements
System.out.println("Unique Elements: "+uniqueElements);
As we see from the sample output, only the unique elements were printed out from the Stream.
Unique Elements: [Java, Code, Depot, Samples, Tutorials]