【发布时间】:2021-09-26 12:32:25
【问题描述】:
我有一个这样的简单代码
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamSupplierVersusConcat {
public static void main(String[] args) {
final StreamSupplierVersusConcat clazz = new StreamSupplierVersusConcat();
clazz.doConcat();
}
private void doConcat(){
System.out.println(Stream.concat(buildStreamFromRange(0,1000).get()
,buildStreamFromRange(1000,2000).get())
.anyMatch("1"::equals));
}
private Supplier<Stream<String>>buildStreamFromRange(final int start,final int end){
return ()->IntStream.range(start, end)
.mapToObj(i->{
System.out.println("index At: "+i);
return String.valueOf(i);
});
}
}
我知道 concat 是惰性的,所以当我运行代码时,我看到它只生成 2 个很棒的值,但知道 distinct 是一个有状态的操作,我认为将该方法放在 Stream 管道上,它将由 Stream 生成所有值,然后执行 anyMatch 方法,但如果我这样说
private void doConcat(){
System.out.println(Stream.concat(buildStreamFromRange(0,1000).get()
,buildStreamFromRange(1000,2000).get())
.distinct()//ARE ALL THE VALUES GENERATED NOT REQUIRED HERE???
.anyMatch("1"::equals));
}
但是有了不同的和没有它,我得到了相同的响应。
index At: 0
index At: 1
true
我错过了什么? 我认为 distinct 会在 anyMatch 看到之前消耗所有项目。 在 Java 8 上测试。
非常感谢。
继续我的理解,我认为 distinct 会在 anyMatch 看到 any 之前看到所有项目。这个例子解释它是不正确的。
private void distinctIsNotABlockingCall(){
final boolean match = Stream.of("0","1","2","3","4","5","6","7","8","8","8","9","9","9","9","9","9","9","9","9","10","10","10","10")
.peek(a->System.out.println("before: "+a))
.distinct()//I THOUGHT THAT NOT ANYMATCH WAS CALLED AFTER DISTINCT HANDLE ALL THE ITEMS BUT WAS WRONG.
.peek(a->System.out.println("after: "+a))
.anyMatch("10"::equals);
System.out.println("match? = " + match);
}
before: 0
after: 0
before: 1
after: 1
before: 2
after: 2
before: 3
after: 3
before: 4
after: 4
before: 5
after: 5
before: 6
after: 6
before: 7
after: 7
before: 8
after: 8
before: 8 distinct working
before: 8 distinct working
before: 9
after: 9
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 9 distinct working
before: 10
after: 10
match? = true
您可以看到 distinct 接收到重复和非重复值,但 anyMatch 也在接收这些非重复值,并且 distinct 和 anyMatch 正在同时工作,非常感谢。
【问题讨论】:
标签: java java-8 java-stream distinct-values