如何在
java8(可能是memoization进程)中重用已经通过流迭代计算的值?
如果流重复或再次提供,则将重新计算.在某些情况下,最好为该CPU时间交换内存.从一开始就收集所有内容可能不是一个好主意,因为流用于查找满足谓词的第一个项目.
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());
问题是simille到Copy a stream to avoid “stream has already been operated upon or closed” (java 8)
最佳答案 为什么不在veryLongTimeToComputeFunction中使用memoization?您可以将memo缓存作为参数添加到func中.