How can I reuse in java8 (maybe a memoization process) values already computed through iteration over a stream?
If the stream is duplicated or supplied again it will be recomputed. In some cases it would be preferable to trade memory for that cpu time. Collecting everything from the beginning might not be a good idea since the stream is used to find the first item that satisfies a predicate.
Stream<Integer> all = Stream.of(1,2,3,4,5, ...<many other values>... ).
map(x->veryLongTimeToComputeFunction(x));
System.out.println("fast find of 2"+all.filter(x->x>1).findFirst());
//both of these two lines generate a "java.lang.IllegalStateException: stream has already been operated upon or closed"
System.out.println("no find"+all.filter(x->x>10).findFirst());
System.out.println("find again"+all.filter(x->x>4).findFirst());
The question is simillar to Copy a stream to avoid "stream has already been operated upon or closed" (java 8)