Reusing Stream by Supplier

240 Views Asked by At

I need to use one stream mutliple times. I tried something like this:

public static void main(String[] args) {

    Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8});
    Supplier<Stream<Integer>> saved = saveStream(stream.filter(e -> e % 2 == 0));

    System.out.println(saved.get().count());
    System.out.println(saved.get().max(Integer::compareTo).get());
    System.out.println(saved.get().min(Integer::compareTo).get());
}

public static Supplier<Stream<Integer>> saveStream(Stream<Integer> stream){
    Supplier<Stream<Integer>> result = new Supplier<Stream<Integer>>() {

        @Override
        public Stream<Integer> get() {
            Stream<Integer> st = stream;
            return st;
        }
    };

    return result;
}

But it doesn't work...

Any suggestion?

1

There are 1 best solutions below

0
On

Your supplier does not create a new instance of the stream, but supplies the same one multiple times.

As a stream is single use only this approach does not work. You have to recreate the stream.