Java 8 Stream IllegalStateException: Stream has already been operated on or closed(Java 8 Stream IllegalStateException:流已经被操作或关闭)
问题描述
我正在尝试使用 Stream API 生成 Order 实例.我有一个创建订单的工厂函数,一个 DoubleStream 用于初始化订单的金额.
private DoubleStream doubleStream = new Random().doubles(50.0, 200.0);私人订单 createOrder() {return new Order(doubleStream.findFirst().getAsDouble());}@测试公共无效测试(){流<顺序>orderStream = Stream.generate(() -> {返回创建订单();});orderStream.limit(10).forEach(System.out::println);
如果我使用文字 (1.0) 初始化 Order 实例,则可以正常工作.当我使用 doubleStream 创建一个随机量时,会抛出异常.
答案在 Stream
的 javadoc 中(重点是我的):
一个流只能被操作一次(调用中间或终端流操作).例如,这排除了分叉"流,其中相同的源提供两个或多个管道,或者同一流的多次遍历.如果检测到流正在被重用,流实现可能会抛出 IllegalStateException.
在您的代码中,您确实使用了两次流(一次在 createOrder()
中,另一次在 .limit().forEach()
中使用p>
I'm trying to generate Order instances using the Stream API. I have a factory function that creates the order, and a DoubleStream is used to initialize the amount of the order.
private DoubleStream doubleStream = new Random().doubles(50.0, 200.0);
private Order createOrder() {
return new Order(doubleStream.findFirst().getAsDouble());
}
@Test
public void test() {
Stream<Order> orderStream = Stream.generate(() -> {
return createOrder();
});
orderStream.limit(10).forEach(System.out::println);
If I initialize the Order instance using a literal (1.0), this works fine. When I use the doubleStream to create a random amount, the exception is thrown.
The answer is in the javadoc of Stream
(emphases mine):
A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused.
And in your code, you do use the stream twice (once in createOrder()
and the other usage when you .limit().forEach()
这篇关于Java 8 Stream IllegalStateException:流已经被操作或关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 Stream IllegalStateException:流已经被操作或关闭
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01