Java9新特性系列(Stream改進)

史培培發表於2019-01-18
Java9新特性系列(Stream改進)

Java8的Stream

在Java8中,一個比較大的變化就是流(Stream),具體可以看之前的一篇文章:Java8新特性系列(Stream)

Java9的Stream

Java9中Stream增加了4個方法,分別是:

  • takeWhile:在有序的Stream中,takeWhile返回從開頭開始的儘量多的元素
default Stream<T> takeWhile(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    // Reuses the unordered spliterator, which, when encounter is present,
    // is safe to use as long as it configured not to split
    return StreamSupport.stream(
        new WhileOps.UnorderedWhileSpliterator.OfRef.Taking<>(spliterator(), true, predicate),
            isParallel()).onClose(this::close);
}
複製程式碼
  • dropWhile:與takeWhile相反
default Stream<T> dropWhile(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    // Reuses the unordered spliterator, which, when encounter is present,
    // is safe to use as long as it configured not to split
    return StreamSupport.stream(
        new WhileOps.UnorderedWhileSpliterator.OfRef.Dropping<>(spliterator(), true, predicate),
            isParallel()).onClose(this::close);
}
複製程式碼
  • ofNullable:可以建立一個單元素Stream,可以為null
public static<T> Stream<T> ofNullable(T t) {
    return t == null ? Stream.empty()
         : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
複製程式碼
  • iterate
public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
    Objects.requireNonNull(f);
    Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,
    Spliterator.ORDERED | Spliterator.IMMUTABLE) {
        T prev;
        boolean started;

        @Override
        public boolean tryAdvance(Consumer<? super T> action) {
            Objects.requireNonNull(action);
            T t;
            if (started)
                t = f.apply(prev);
            else {
                t = seed;
                started = true;
            }
            action.accept(prev = t);
            return true;
        }
    };
    return StreamSupport.stream(spliterator, false);
}
複製程式碼

除了對 Stream 本身的擴充套件,Optional和Stream之間的結合也得到了改進,可以將optional物件轉化為stream物件:

List<String> list = new ArrayList<>() {{
    add("a");add("b");add("c");
}};
Optional<List<String>> optional = Optional.ofNullable(list);
Stream<List<String>> stream = optional.stream();
stream.flatMap(x -> x.stream()).forEach(System.out::println);
複製程式碼

使用舉例

  • takeWhile
List<Integer> list = Arrays.asList(1, 4, 5, 2, 3, 6, 7, 8, 9, 10);
list.stream().takeWhile(x -> x < 5).forEach(System.out::println);
複製程式碼

輸出:
1
4

  • dropWhile
List<Integer> list = Arrays.asList(1, 4, 5, 2, 3, 6, 7, 8, 9, 10);
list.stream().dropWhile(x -> x < 5).forEach(System.out::println);
複製程式碼

輸出:
5
2
3
6
7
8
9
10

  • ofNullable
Stream<String> stream = Stream.of("", null);
System.out.println(stream.count());

Stream<String> stream = Stream.of(null);
System.out.println(stream.count());//會拋空指標異常

Stream<String> stream = Stream.ofNullable(null);
System.out.println(stream.count());
複製程式碼

輸出:
2
0

  • iterate
//java8
Stream.iterate(1, i -> i + 1).limit(5).forEach(System.out::println);

//java9
Stream.iterate(1, i -> i < 6, i -> i + 1).forEach(System.out::println);
複製程式碼

輸出:
1
2
3
4
5

Java9新特性系列(Stream改進)

微信公眾號:碼上論劍

請關注我的個人技術微信公眾號,訂閱更多內容

相關文章