问题描述
我正在尝试使用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):
并在您的代码中,你确实使用了两次流(一次在 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已经被操作或关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!