Java Stream: More APIs

using distinct()

The distinct API returns a new Stream which will only contain the distinct elements from the original stream.

Screen Shot 2020-02-04 at 8.01.12 PM

Output

Screen Shot 2020-02-04 at 8.06.09 PM

Using limit()

The limit API returns a new Stream which will at most contain the given number of elements.

Screen Shot 2020-02-04 at 8.11.18 PM

Output

Screen Shot 2020-02-04 at 8.11.25 PM

Using peek()

peek API returns new Stream consisting of the elements of original stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

peek API does not transform or filter the elements in the stream. This method exists mainly to support debugging, where we want to see the elements as they flow past a certain point in a pipeline.

Screen Shot 2020-02-04 at 8.52.48 PM

Output

Screen Shot 2020-02-04 at 8.52.57 PM

anyMatch()

anyMatch API takes a single Predicate as parameter. If the Predicate returns true for any of the elements, the anyMatch() method returns true. If no elements match the Predicate, anyMatch() will return false.

Screen Shot 2020-02-04 at 8.59.53 PM

Output

Screen Shot 2020-02-04 at 9.00.00 PM

allMatch()

allMatch API takes a single Predicate as parameter. If the Predicate returns true for all elements in the Stream, the allMatch() will return true. If not all elements match the Predicate, the allMatch() method returns false.

Screen Shot 2020-02-04 at 9.04.02 PM

Output

Screen Shot 2020-02-04 at 9.04.10 PM

noneMatch()

noneMatch API will iterate the elements in the stream and return true or false, depending on whether no elements in the stream matches the Predicate passed to noneMatch() as parameter.

Screen Shot 2020-02-04 at 9.02.26 PM

Output

Screen Shot 2020-02-04 at 9.02.34 PM

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *