Skip to content

Commit f5d493f

Browse files
author
1399852153
committed
java实现 流
1 parent 70c3fa8 commit f5d493f

3 files changed

Lines changed: 24 additions & 9 deletions

File tree

src/main/java/second/stream/Process.java

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,6 @@ public class Process {
1212

1313
EvalFunction evalFunction;
1414

15-
public Process(Process next, EvalFunction evalFunction) {
16-
this.next = next;
17-
this.evalFunction = evalFunction;
18-
}
19-
2015
public Process(EvalFunction evalFunction) {
2116
this.evalFunction = evalFunction;
2217
}

src/main/java/second/stream/Stream.java

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,15 @@ public Stream<T> filter(Predicate<T> predicate) {
8989

9090
@Override
9191
public Stream<T> limit(int n) {
92-
return null;
92+
Process lastProcess = this.process;
93+
this.process = new Process(
94+
()-> {
95+
Stream stream = lastProcess.eval();
96+
return limit(n,stream);
97+
}
98+
);
99+
100+
return this;
93101
}
94102

95103
@Override
@@ -146,6 +154,17 @@ private <R> R reduce(R initVal,Accumulate<R,T> accumulator,Stream<T> stream){
146154
return accumulator.apply(result,head);
147155
}
148156

157+
private Stream<T> limit(int num,Stream<T> stream){
158+
if(num == 0){
159+
return StreamInterface.makeEmptyStream();
160+
}
161+
162+
return new Stream.Builder<T>()
163+
.head(stream.head)
164+
.process(new Process(()->limit(num-1,stream.eval())))
165+
.build();
166+
}
167+
149168
private Stream<T> eval(){
150169
return this.process.eval();
151170
}

src/test/java/TestStream2.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ public class TestStream2 {
1111
public static void main(String[] args){
1212
Stream<Integer> intStream = StreamGenerator.getIntegerStream(10);
1313

14-
intStream = intStream.filter(TestStream2::idOdd);
15-
intStream = intStream.map(TestStream2::scaleTwo);
16-
intStream = intStream.map(TestStream2::square);
14+
// intStream = intStream.filter(TestStream2::idOdd);
15+
// intStream = intStream.map(TestStream2::scaleTwo);
16+
// intStream = intStream.map(TestStream2::square);
17+
// intStream = intStream.limit(3);
1718

1819
Integer sum = intStream.reduce(0,(v1,v2) -> v1 + v2);
1920

0 commit comments

Comments
 (0)