logo

Stream API Improvements


Show

Streams were initiated in java to help developers perform a collection of operations from a sequence of objects. Few more methods are added to make streams better with java 9.

takeWhile (Predicate Interface)

Syntax

default Stream<T> takeWhile(Predicate<? super T> predicate)

takeWhile method takes all the values up to predicate returns false. It returns, in case or ordered stream, a stream consisting of the biggest prefix of elements that get hold of from this stream matching the given predicate.

Example

import java.util.stream.Stream;

public class Tester {
   public static void main(String[] args) {
      Stream.of("a","b","c","","e","f").takeWhile(s->!s.isEmpty())
         .forEach(System.out::print);  
   } 
}

Output

takeWhile way takes all a,b and c values, then once the string is empty it pauses executing.

abc

dropWhile(Predicate Interface)

Syntax

default Stream<T> dropWhile(Predicate<? super T> predicate)

drop while a method to lob away all the values at the start-up to the predicate returns true. It gives back, in the case of an ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of components matching the given predicate.

Example

import java.util.stream.Stream;

public class Tester {
  public static void main(String[] args) {
      Stream.of("a","b","c","","e","f").dropWhile(s-> !s.isEmpty())
         .forEach(System.out::print);    

      System.out.println();
      Stream.of("a","b","c","","e","","f").dropWhile(s-> !s.isEmpty())
         .forEach(System.out::print);
   } 
}

Output

dropwhile method drops a,b,and c values, then once the string becomes empty it will take all the values.

ef
ef

iterate

Syntax

static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

iterate now has hasnextPredicate as parameter which pauses the loop once hasNextPredicate returns false.

Example

import java.util.stream.IntStream;

public class Tester {
  public static void main(String[] args) {
      IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println);
   } 
}

Output

3
6
9

OffNullable

Syntax

static <T> Stream<T> ofNullable(T t)

ofNullable method is launched to prevent NullPointersExceptions and to avoid null checks for streams. This method returns a sequential stream holding a single element, if non-null, otherwise gives back an empty stream.

Example

import java.util.stream.Stream;
public class Tester {
   public static void main(String[] args) {
      long count = Stream.ofNullable(100).count();
      System.out.println(count);
  
      count = Stream.ofNullable(null).count();
      System.out.println(count);
   } 
}

Output

1
0