New Stream operations in Java 9

/, Java 9/New Stream operations in Java 9

New Stream interface operations in Java 9:

In Java 9, Stream interface has the following new methods. In this guide we explained about the new Stream operations in java 9.

dropWhile:

  1. The method dropWhile drops elements in the stream until it encounters the first element that doesn’t match the predicate.
  2. For unordered stream the behavior of dropWhile() non-deterministic. The current implementation drops the matching elements from the beginning until it finds a non matching element.
  3. If the first element does not match the predicate, the dropWhile method returns original stream.
  4. If all elements match the predicate, the method returns an empty stream.

Output:

takeWhile:

  1. The method takeWhile performs the opposite action on a stream as to dropWhile. takeWhile() takes elements in the stream until it it matches the first
    element that doesn’t match the predicate.
  2. takeWhile() has the same behavior as dropWhile() when processing ordered and unordered streams.

Output:

ofNullable:

  1. The method ofNullable returns a Stream of zero or one element, depends on if the input value is null.
  2. Below example demonstrates how to get non-null values from a list using ofNullable method.

Output:

iterate:

  1. The static method iterate(T seed, Predicate<? super T> hasNext, UnaryOperator next) is a new way to generate streams using the iterator pattern.
  2. seed is the initial element for iteration hasNext is the predicate that applies to the current element to check if the stream should be terminated, next is the function that applies to the current element to produce the next element
    in the stream.
  3. If the initial element seed doesn’t match the predicate hasNext, the result stream is empty.

Output: