Java 8 Stream IllegalStateException: Stream has already been operated on or closed

前端 未结 6 611
孤独总比滥情好
孤独总比滥情好 2020-11-27 07:45

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 o

相关标签:
6条回答
  • 2020-11-27 08:19

    Thank you - that was very helpful. I also came up with a different implementation that works well for now:

    private DoubleStream doubleStream = new Random().doubles(50.0, 200.0);
    
    private List<Order> createOrders(int numberOfOrders) {
    List<Order> orders = new ArrayList<>();
    doubleStream.limit(numberOfOrders).forEach((value) -> {
        Order order = new Order(value);
        orders.add(order);
    });
    return orders;
    }
    

    Thanks again!

    Ole

    0 讨论(0)
  • 2020-11-27 08:20

    As fge states, you can't (shouldn't) consume a Stream more than once.

    Any idea how to fix this?

    From the Javadoc of Random#doubles(double, double)

    A pseudorandom double value is generated as if it's the result of calling the following method with the origin and bound:

    double nextDouble(double origin, double bound) {
        double r = nextDouble();
        r = r * (bound - origin) + origin;
        if (r >= bound) // correct for rounding
           r = Math.nextDown(bound);
        return r;
    }
    

    Implement such a method and use it to get a new double value each time you need one instead of trying to get it from a DoubleStream. Possibly use a DoubleSupplier.

    private final Random random = new Random();
    private DoubleSupplier supplier = () -> nextDouble(random, 50.0, 200.0);
    
    private Order createOrder() {
    
        return new Order(supplier.getAsDouble());
    }
    
    private static double nextDouble(Random random, double origin, double bound) {
        double r = random.nextDouble();
        r = r * (bound - origin) + origin;
        if (r >= bound) // correct for rounding
            r = Math.nextDown(bound);
        return r;
    }
    

    If you're not going to reuse the nextDouble method, you can inline the values 50.0 and 200.0.

    0 讨论(0)
  • 2020-11-27 08:21

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

    0 讨论(0)
  • 2020-11-27 08:24

    Your method could be a one-liner like this instead. You need to use mapToObj, not map

    private List<Order> createOrders(int numberOfOrders) {
         return doubleStream.limit(numberOfOrders).mapToObj(Order::new).collect(Collectors.toList());
    }
    
    0 讨论(0)
  • 2020-11-27 08:34

    As said in other answers, Streams are single-use items and you have to create a new Stream each time you need one.

    But, after all, this isn’t complicated when you remove all your attempts to store intermediate results. Your entire code can be expressed as:

    Random r=new Random(); // the only stateful thing to remember
    
    // defining and executing the chain of operations:
    r.doubles(50.0, 200.0).mapToObj(Order::new).limit(10).forEach(System.out::println);
    

    or even simpler

    r.doubles(10, 50.0, 200.0).mapToObj(Order::new).forEach(System.out::println);
    
    0 讨论(0)
  • 2020-11-27 08:43

    You should use Supplier function interface for your initialization like this

    Supplier<Stream<Double>> streamSupplier = () -> (new Random().doubles(50.0, 200.0).boxed());
    

    And change your way to get double like this

    streamSupplier.get().findFirst().get()
    

    Then it works normally.

    Found this way from the post Stream has already been operated upon or closed Exception

    0 讨论(0)
提交回复
热议问题