Core Java

Java 9: Enhancements to the Stream API

Java 9 adds 4 new methods to the Stream interface:

1. dropWhile

The dropWhile method is similar to the skip method but uses a Predicate instead of a fixed integer value. It drops elements from the input stream while the Predicate is true. All remaining elements are then passed to the output stream. For example:

IntStream.range(0, 10)
         .dropWhile(i -> i < 5)
         .forEach(System.out::println);
// prints 5, 6, 7, 8, 9

2. takeWhile

The takeWhile method is similar to the limit method. It takes elements from the input stream and passes them to the output stream while the Predicate is true. For example:

IntStream.range(0, 10)
         .takeWhile(i -> i < 5)
         .forEach(System.out::println);
// prints 0, 1, 2, 3, 4

Note: Be careful when usingdropWhile and takeWhile when you have an unordered stream because you might get elements in the output stream that you don’t expect.

3. ofNullable

The ofNullable method returns an empty stream if the element is null, or a single-element stream if non-null. This eliminates the need for a null check before constructing a stream.

Stream.ofNullable(null).count();  // prints 0
Stream.ofNullable("foo").count(); // prints 1

4. iterate

The static iterate method has been overloaded in Java 9 to allow you to create a stream using the for-loop syntax. For example:

Stream.iterate(0, i -> i < 10, i -> i + 1)
      .forEach(System.out::println); //prints from 0 to 9
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 9: Enhancements to the Stream API

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button