Java 8 Stream IllegalStateException:Stream已经被操作或关闭 [英] Java 8 Stream IllegalStateException: Stream has already been operated on or closed

查看:293
本文介绍了Java 8 Stream IllegalStateException:Stream已经被操作或关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Stream API生成订单实例。我有一个创建订单的工厂函数,DoubleStream用于初始化订单金额。

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

如果我使用文字(1.0)初始化Order实例,这样可以正常工作。当我使用doubleStream创建一个随机数量时,抛出异常。

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.

任何想法如何解决这个问题?

Any idea how to fix this?

TIA,

Ole

推荐答案

答案是的javadoc(强调我的):

The answer is in the javadoc of Stream (emphases mine):


流应该是只能操作一次(调用中间或终端流操作)。例如,这排除了分叉流,其中相同的源提供两个或更多个管道,或者同一个流的多个遍历。 如果流实现检测到正在重用,则可能会抛出IllegalStateException。

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.

并在您的代码中,你确实使用了两次流(一次在 createOrder(),另一种用法是 .limit()。forEach()

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:Stream已经被操作或关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆