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
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
.