-1

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?

Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 1
    Streams are single use. – Kayaman Dec 20 '19 at 11:09
  • Try reading the [documentation on Streams](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) especially the part about terminal operations. – Nicktar Dec 20 '19 at 11:13
  • Looks like an instance of [Cargo Cult](https://en.wikipedia.org/wiki/Cargo_cult_programming). You use a `Supplier`, but don’t really know why. – Holger Dec 20 '19 at 16:10

1 Answers1

1

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.

sbleden
  • 11
  • 1