Java – Stream has already been operated upon or closed

package com.mkyong.java8;

import java.util.Arrays;
import java.util.stream.Stream;

public class TestJava8 {

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));

// reuse it to filter again! throws IllegalStateException
long count = stream.filter(x -> "b".equals(x)).count();
System.out.println(count);

}

}

Output

java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
at java.util.stream.ReferencePipeline.(ReferencePipeline.java:94)
at java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:618)
at java.util.stream.ReferencePipeline$2.(ReferencePipeline.java:163)
at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
at com.hostingcompass.whois.range.run.TestJava8.main(TestJava8.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

2. Example – Reuse a stream
package com.mkyong.java8;

import java.util.function.Supplier;
import java.util.stream.Stream;

public class TestJava8 {

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);

}

}
Output

a
b
c
d
e
1

http://www.mkyong.com/java8/java-stream-has-already-been-operated-upon-or-closed/

最新文章

  1. nodejs处理url工具
  2. python发邮件
  3. 迭代加深搜索 POJ 1129 Channel Allocation
  4. css 标签 清除浮动
  5. Oracle升级前备份和失败回退
  6. java多线程浅谈
  7. SharePoint 2013 自定义翻页显示列表项
  8. 为什么国外程序员爱用Mac?
  9. JavaScript之数组学习
  10. javascript 函数的4种调用方式与 this(上下文)的指向
  11. [原创] JAVA 递归线程池测试 ExecutorService / ForkJoinPool
  12. maven 聚合工程 用spring boot 搭建 spring cloud 微服务 模块式开发项目
  13. 解决openoffice进程异常退出的办法
  14. 为什么HTTPS比HTTP安全,以及两者的优缺点
  15. JavaScript从入门到精通(附光盘1张):作者:明日科技出版社:清华大学出版社出版时间:2012年09月
  16. Lodop调整打印项输出顺序 覆盖与层级
  17. File类总结
  18. springboot报错Whitelabel Error Page
  19. C#访问远程主机资源的方法
  20. 面向对象设计原则 迪米特法则(Law of Demeter)

热门文章

  1. JERSEY中文翻译(第一章、Getting Started、1.1.7)
  2. 运用BufferedWriter把数据写入文件
  3. flow 静态类型检查 js
  4. nginx 和php设置上传大小及可以提交的内容限制
  5. 【PMP】财务测量指标ROI、PBP、NPV、IRR、BCR
  6. SpringMVC 参数中接收数组、List写法
  7. QTableView中使用Delegate方式来实现对特定列的文本进行换行
  8. 如何配置pl/sql 连接远程oracle服务器
  9. 客户端调用rcf库 时,返回值千万不要用auto
  10. Out of memory error : GC overhead limit exceeded