Java 9 Stream API Improvements

Posted on

Four new operations are added to Stream API in Java 9. They are – takeWhile(), dropWhile(), ofNullable() and iterate().

takeWhile() : If calling stream is ordered, then this method returns a stream containing first n elements of the calling stream which satisfy the given predicate. If the calling stream is unordered then this method returns all or some elements which satisfy the given predicate.

dropWhile() : This method is total opposite of takeWhile(). This method drops first n elements which satisfy the given predicate and returns remaining elements if the calling stream is ordered. If the calling stream is unordered, then this method returns remaining elements after dropping the elements which satisfy the given predicate.

ofNullable() : This method takes one element as an argument and returns a Stream containing that single element if the passed element is non-null. If the passed element is null, it returns an empty Stream.

iterate() : iterate() method is already there in Stream interface from Java 8. But, Java 9 provides another version of iterate() method which takes an extra argument hasNext of type Predicate which decides when to terminate the operation.

For examples how to use these methods, see this post : https://javaconceptoftheday.com/java-9-stream-api-improvements-takewhile-dropwhile-ofnullable-and-iterate/.

Leave a Reply

Your email address will not be published.