我在学习Stream.limit()
说:
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
这可以从以下方面理解:
Stream.of(1,2,3,4,5,6,7,8)
.limit(3)
.forEach(i -> {
System.out.print(i + ",");
}); //prints: 1,2,3,
但是与其他流方法一起使用时,它具有批量处理元素的效果:
Stream.of(1,2,3,4,5,6,7)
.filter(i -> {
System.out.println("Filtering " + i + ": " + (i%2 == 0));
return i%2 == 0;
})
.map(i-> {
System.out.println("Mapping " + i + " to " + i*i);
return i*i;
})
.limit(2)
.forEach(i -> System.out.println("---> " + i));
打印:
Filtering 1: false
Filtering 2: true
Mapping 2 to 4
---> 4
Filtering 3: false
Filtering 4: true
Mapping 4 to 16
---> 16
在这里,您可以看到元素以 2 个为一组进行处理。
我有以下疑问:
为什么它不只处理前两个元素 1 和 2?也就是说,为什么输出不只是:
Filtering 1: false Filtering 2: true Mapping 2 to 4 ---> 4
为什么它没有处理最后四个元素 5、6、7 和 8 并打印以下内容?:
Filtering 5: false Filtering 6: true Mapping 6 to 36 ---> 36 Filtering 7: false Filtering 8: true Mapping 8 to 64 ---> 64
最佳答案
1
和2
均已处理。1
是奇数,因此filter
将其从流管道中移除。2
是偶数并通过整个流管道导致4
在forEach
中打印出来。流本质上是惰性的。由于您使用了
limit(2)
,因此只有两个元素可以通过limit
管道步骤。2
和4
遍历了整个流管道,导致4
和16
在forEach< 中打印出来
.
limit()
是短路状态中间操作,根据 docs :
Short-circuiting operations such as limit(n) or findFirst() can allow computations on infinite streams to complete in finite time.
...
Further, some operations are deemed short-circuiting operations. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time. Having a short-circuiting operation in the pipeline is a necessary, but not sufficient, condition for the processing of an infinite stream to terminate normally in finite time.
关于java - 了解 java Stream.limit() 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52986128/