Java8 Stream 已經被操作或關閉


引言

在 java8 中,Stream 不能被重用,一旦它被使用或使用,流將被關閉。

1. 流關閉

查看下面的示例,它將拋出一個 IllegalStateException,表示“ stream is closed”。

public static void main(String[] args) {
    String[] array = {"a", "b", "c", "d", "e"};
    Stream<String> stream = Arrays.stream(array);

    // loop a stream
    stream.forEach(x-> System.out.println(x));

    // 拒絕過濾,拋出 throws IllegalStateException
    long count = stream.filter(x -> "b".equals(x)).count();
    System.out.println(count);
  }

輸出:

a
b
c
d
e
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203)
	at java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:94)
	at java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:618)
	at java.util.stream.ReferencePipeline$2.<init>(ReferencePipeline.java:163)
	at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
	at com.jimzhang.stream.ClosedTest.main(ClosedTest.java:22)

2. 重用流

不管出於什么原因,你真的想重用一個數據流,試試下面的 Supplier 解決方案:

public static void main(String[] args) {

    String[] array = {"a", "b", "c", "d", "e"};
    Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);

    //get new stream
    streamSupplier.get().forEach(x-> System.out.println(x));

    //get another new stream

    long count = streamSupplier.get().filter(x -> "b".equals(x)).count();
    System.out.println(count);
  }

輸出:

a
b
c
d
e
1

每個 get ()將返回一個新的流。

源碼見:java-8-demo

系列文章詳見:Java 8 教程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM