6
6
import com .github .lokic .javaplus .tuple .Tuple2 ;
7
7
import com .github .lokic .javaplus .tuple .Tuple3 ;
8
8
9
+ import java .util .ArrayList ;
10
+ import java .util .List ;
11
+ import java .util .Spliterator ;
12
+ import java .util .Spliterators ;
9
13
import java .util .concurrent .ConcurrentHashMap ;
10
14
import java .util .concurrent .ConcurrentMap ;
15
+ import java .util .function .Consumer ;
11
16
import java .util .function .Function ;
17
+ import java .util .function .Supplier ;
18
+ import java .util .stream .Stream ;
19
+
20
+ import static java .util .stream .StreamSupport .stream ;
12
21
13
22
/**
14
23
* 对执行的函数提供记忆化的功能,减少相同参数的重复调用
@@ -30,4 +39,41 @@ public static <T1, T2, T3, R> Function3<T1, T2, T3, R> of(Function3<T1, T2, T3,
30
39
return (t1 , t2 , t3 ) -> cache .computeIfAbsent (Tuple .of (t1 , t2 , t3 ), t -> function3 .apply (t .getT1 (), t .getT2 (), t .getT3 ()));
31
40
}
32
41
42
+
43
+ /**
44
+ * 带缓存功能,可多次重放Stream
45
+ *
46
+ * @param streamSupplier
47
+ * @param <T>
48
+ * @return
49
+ */
50
+ public static <T > Supplier <Stream <T >> of (Supplier <Stream <T >> streamSupplier ) {
51
+ final Spliterator <T > spliterator = streamSupplier .get ().spliterator ();
52
+ final List <T > cache = new ArrayList <>();
53
+ return () -> {
54
+ Spliterator <T > split = new Spliterators .AbstractSpliterator <T >(
55
+ spliterator .estimateSize (), spliterator .characteristics ()) {
56
+
57
+ private int index = 0 ;
58
+ private boolean hasNext = true ;
59
+
60
+ @ Override
61
+ public boolean tryAdvance (Consumer <? super T > action ) {
62
+ int currentIndex = index ++;
63
+ if (currentIndex < cache .size ()) {
64
+ action .accept (cache .get (currentIndex ));
65
+ return true ;
66
+ } else if (hasNext ) {
67
+ hasNext = spliterator .tryAdvance (item -> {
68
+ cache .add (item );
69
+ action .accept (item );
70
+ });
71
+ }
72
+ return hasNext ;
73
+ }
74
+ };
75
+ return stream (split , false );
76
+ };
77
+ }
78
+
33
79
}
0 commit comments