Java 8 Stream Distinct Examples

Today, I walk you through Java 8 Stream Distinct Examples using stream API. You can filter or collect all distinct elements from a collection by using distinct() of Stream API. In case, we have to process a collection of complex objects we need to write a custom function for the specific filtering purpose.

1. Java 8 distinct example
Now, we are finding all distinct strings without case sensitive from the String collection.

Output

2. Java 8 stream distinct by key

Above distinct example is quite simple and easy for us. In fact, we need to deal with objects or complex types.

We’re considering a POJO as below

Until now, Java doesn’t support any native API for filtering distinct by object property directly, even date object. We have to create a utility function which matches with our requirement. Our utility function will filter distinct by the name property of People object, like this.

Here is a function that returns a predicate that maintains state about what it’s seen previously, and that returns whether the given element was seen for the first time.

Writting the demo program:

Output

Java 8 Stream Distinct Examples

That’s all about the Java 8 Stream Distinct Examples.

References
Processing Data with Java SE 8 Streams

Download the complete source code, click link below

Java8StreamDistinctExamples.zip (6 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons