Jayson
Jayson

Reputation: 91

Stream IllegalStateException

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)

Upvotes: 1

Views: 1311

Answers (2)

Laguh
Laguh

Reputation: 673

In Java 8 each Stream is a single-use sequence of data that supports several I/O operations in pipeline.

After the end of the piped operations, the stream instance gets consumed and closed.

If you try to use the same stream one more time at another part of your code, you will get java.lang.IllegalStateException: stream has already been operated upon or closed

In your code you are using it twice: - instream.count() and instream.map()

Upvotes: 1

Vinz243
Vinz243

Reputation: 9938

Using intstream.count() closes the stream (because it needs to process the whole stream in order to count the number of elements). However, your check is totally unecessary because it already returns an optional which will be empty if the stream is.

Upvotes: 3

Related Questions