import java.util.Random;
public class Main {
public static void main(String[] args) {
new Random().ints(1, 45 + 1) // (1)
.distinct() // (2)
.limit(6)
.sorted()
.forEach(System.out::println);
}
}new Random().ints是无限流。
我想,无限的溪流是无法区分的,因为无限的溪流在继续增长。
但这个代码是有可能的。
它是怎么工作的?
发布于 2022-03-10 11:42:34
因为.limit(6)的结果并不是无限的。流并不能对每个操作产生全部结果。
发布于 2022-03-10 12:03:32
流建立在懒惰评估的概念之上。这意味着在应用下一个运算符之前,每个操作符(在您的示例中是distinct)都不会使用完整的元素流。
因此,流的每个元素都通过所有操作符,直到到达终端操作符为止。然后,流的下一个元素再次通过所有操作符,直到到达终端操作符为止。这就是您的操作符distinct能够处理提供的无限流的原因。
limit是在您的情况下使用的终端操作符。您可以通过使用peek拦截这些元素来观察它是如何工作的。检查以下内容,您将能够理解流如何在懒散的概念中工作,就像前面所说的,直到它们到达终端操作员为止。
new Random().ints(1, 45 + 1) // (1)
.peek(el -> System.out.println("Before distinct " + el))
.distinct() // (2)
.peek(el -> System.out.println("After distinct " + el))
.limit(6)
.peek(el -> System.out.println("After limit " + el))
.sorted()
.forEach(System.out::println);将打印
Before distinct 8
After distinct 8
After limit 8
Before distinct 45
After distinct 45
After limit 45
Before distinct 16
After distinct 16
After limit 16
Before distinct 34
After distinct 34
After limit 34
Before distinct 9
After distinct 9
After limit 9
Before distinct 25
After distinct 25
After limit 25 <---- Here the limit of 6 elements is covered so the first stream is completed.
8
9
16
25
34
45也可以看看这个SO answer,看看过去类似的调查。
https://stackoverflow.com/questions/71423545
复制相似问题