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 containing stateful intermediate operations may require multiple passes on the data or may need to buffer significant data...').
  • filter(): This method receives a Predicate as parameter. This predicate can be expressed as a lambda expression that returns a boolean value. The filter() method returns a stream with the elements that make the Predicate true.
  • limit(): This method receives an int value as a parameter and returns a stream with no more than as many number of elements. The performance of this method can also be bad with ordered parallel streams, especially when the number of elements you want to get is big, because the method will return the first elements of the stream and that will imply additional computation. This circumstance doesn't occur with unordered streams because in that case, it doesn't matter what elements are returned.
  • skip(): This method returns a stream with the elements of the original stream after discarding the first elements. The number of discarded elements is specified as the parameter of this method. This method has the same performance problems as with the limit() method.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.116.59