Java 9 - Stream API Improvements


With Java 9, couple of more strategies are added to make streams better.

Limiting Stream with takeWhile() and dropWhile() methods

The new techniques takeWhile and dropWhile enable you to get parts of a stream dependent on a predicate. Here a stream can be either requested or unordered, so :

  1. On an arranged stream, takeWhile restores the "longest prefix" of components taken from the stream that coordinate the given predicate, beginning toward the start of the stream.
  2. On an un-requested stream, takeWhile restores a subset of the stream's components that coordinate the given predicate (yet not all), beginning toward the start of the stream.
  3. takeWhile(Predicate Interface)

    Syntax

    default Stream<T> takeWhile(Predicate<? super T> 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 method takes all a, b, and c values, then once string is empty, it stopped executing.

    abc
    

    dropWhile(Predicate Interface)

    Syntax

    default Stream<T> dropWhile(Predicate<? super T> 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 string is empty, it takes all the values.

    ef
    ef
    

    iterate

    Syntax

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

    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
    

    ofNullable

    Syntax

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

    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
    





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition