Java 9 - Stream API Improvements


With Java 9, few more methods are added to make streams better.

Limiting Stream with takeWhile() and dropWhile() methods

The new methods takeWhile and dropWhile allow you to get portions of a stream based on a predicate. Here a stream can be either ordered or unordered, so :

  1. On an ordered stream, takeWhile returns the “longest prefix” of elements taken from the stream that match the given predicate, starting at the beginning of the stream.
  2. On an un-ordered stream, takeWhile returns a subset of the stream’s elements that match the given predicate (but not all), starting at the beginning 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