Skip to content

Commit 7d6845d

Browse files
count 实现
1 parent 6b931cc commit 7d6845d

3 files changed

Lines changed: 26 additions & 1 deletion

File tree

src/main/java/stream/MyStream.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,11 @@ public T min(Comparator<T> comparator) {
173173
}
174174
}
175175

176+
@Override
177+
public int count() {
178+
return count(this.eval(),0);
179+
}
180+
176181
//===============================私有方法====================================
177182

178183
/**
@@ -343,6 +348,18 @@ private static <T> T min(Comparator<T> comparator, MyStream<T> myStream, T min){
343348
}
344349
}
345350

351+
/**
352+
* 递归函数 配合API.count
353+
* */
354+
private static <T> int count(MyStream<T> myStream, int count){
355+
if(myStream.isEmptyStream()){
356+
return count;
357+
}
358+
359+
// count+1 进行递归
360+
return count(myStream.eval(),count+1);
361+
}
362+
346363
/**
347364
* 当前流强制求值
348365
* @return 求值之后返回一个新的流

src/main/java/stream/Stream.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,12 @@ public interface Stream<T> {
8080
* */
8181
T min(Comparator<T> comparator);
8282

83+
/**
84+
* 计数 eval 强制求值
85+
* @return 当前流的个数
86+
* */
87+
int count();
88+
8389
/**
8490
* 返回空的 stream
8591
* @return 空stream

src/test/java/TestMyStream.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ public static void main(String[] args){
1717

1818
intMyStream = intMyStream.distinct();
1919

20-
intMyStream.forEach(System.out::println);
20+
System.out.println(intMyStream.count());
21+
22+
// intMyStream.forEach(System.out::println);
2123
}
2224

2325
private static boolean idOdd(int num){

0 commit comments

Comments
 (0)