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 教程

转载于:https://my.oschina.net/zjm528el/blog/3100397

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值