English 中文(简体)
Java 9 - Stream API Improvements
  • 时间:2024-11-03

Java 9 - Stream API Improvements


Previous Page Next Page  

Streams were introduced in Java to help developers perform aggregate operations from a sequence of objects. With Java 9, few more methods are added to make streams better.

takeWhile(Predicate Interface)

Syntax

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

takeWhile method takes all the values until the predicate returns false. It returns, in case of ordered stream, a stream consisting of the longest prefix of elements taken from this stream matching the given predicate.

Example

import java.util.stream.Stream;

pubpc class Tester {
   pubpc 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)

dropWhile method throw away all the values at the start until the predicate returns true. It returns, in case of ordered stream, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements matching the given predicate.

Example

import java.util.stream.Stream;

pubpc class Tester {
   pubpc 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)

iterate method now has hasNext predicate as parameter which stops the loop once hasNext predicate returns false.

Example

import java.util.stream.IntStream;

pubpc class Tester {
   pubpc 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)

ofNullable method is introduced to prevent NullPointerExceptions and to avoid null checks for streams. This method returns a sequential Stream containing single element, if non-null, otherwise returns an empty Stream.

Example

import java.util.stream.Stream;

pubpc class Tester {
   pubpc 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
Advertisements