Monday, December 25, 2017

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 using dropWhile 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

No comments:

Post a Comment