Stream.filter()

We can filter a stream using the filter() method. Let's filter the stream obtained from the languages list to filter items starting with E, as shown in the following code:

stream.filter( item -> item.startsWith("E") ); 

The filter() method takes a Predicate as a parameter. The predicate interface contains a function called boolean test(T t) that takes a single parameter and returns a boolean. In the preceding example, we passed the lambda expression item -> item.startsWith("E") to the test() function.

When the filter() method is called on a Stream, the filter passed as a parameter to the filter() function is stored internally. The items are not filtered immediately. 

The parameter passed to the filter() function determines what items in the stream should be processed and what should be excluded. If the Predicate.test() function returns true for an item, that means it should be processed. If false is returned, the item is not processed. In the preceding example, the test() function will return true for all items starting with the character E.

..................Content has been hidden....................

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