How it works...

In this recipe we have used four methods to filter the elements in a stream. These methods are:

  • distinct(): This method returns a stream with the distinct elements of the current stream according to the equals() method of the elements of the Stream class. In our case, we have tested this method with Person objects and int numbers. We have implemented the equals() and hashCode() methods in the Person class. If we don't do this, the equals() method will only return true if the two compared objects hold the same reference. Take into account that this operation is a stateful operation, so it won't get a good performance with parallel streams (as the Java documentation reflects, '... under parallel computation, some pipelines ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.