I am facing this error and have no idea how to debug it. The summary of the question is that I have to get the minimum and maximum of a stream. I cannot use Collections and the stream must be parallelizable. Furthermore, the stream is an argument so it cannot be duplicated. I am not asking for a solution but just what does the error mean.
class MinMax {
final int min, max;
static Optional<MinMax> findMinMax(Stream<Integer> instream) {
if(instream.count() > 0) {
Optional<MinMax> ans = instream.map(x -> {return new MinMax(x,x);}).reduce((x, y) -> {
Integer max = x.max;
Integer min = x.min;
if (y.min < min){
min = y.min;
}
if (y.max > max) {
max = y.max;
}
return new MinMax(min, max);
});
return ans;
} else {
return Optional.empty();
}
}
public MinMax(int min, int max) {
this.min = min;
this.max = max;
}
@Override
public String toString() {
return min + ", " + max;
}
}
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.base/java.util.stream.AbstractPipeline.(AbstractPipeline.java:203) at java.base/java.util.stream.ReferencePipeline.(ReferencePipeline.java:94) at java.base/java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:696) at java.base/java.util.stream.ReferencePipeline$3.(ReferencePipeline.java:189) at java.base/java.util.stream.ReferencePipeline.map(ReferencePipeline.java:188) at MinMax.findMinMax(MinMax.java:11) at Main.main(MinMax.java:46)