java - Stream.of 和 IntStream.range 有什么区别?
问题描述
请考虑以下代码:
System.out.println("#1");
Stream.of(0, 1, 2, 3)
.peek(e -> System.out.println(e))
.sorted()
.findFirst();
System.out.println("\n#2");
IntStream.range(0, 4)
.peek(e -> System.out.println(e))
.sorted()
.findFirst();
输出将是:
#1
0
1
2
3
#2
0
谁能解释一下,为什么两个流的输出不同?
解决方案
好吧,IntStream.range()
返回a sequential ordered IntStream from startInclusive(inclusive) to endExclusive (exclusive) by an incremental step of 1
,这意味着它已经排序。.sorted()
由于它已经排序,因此以下中间操作什么都不做是有道理的。结果,peek()
仅在第一个元素上执行(因为终端操作只需要第一个元素)。
另一方面,传递给的元素Stream.of()
不一定是排序的(并且该of()
方法不检查它们是否已排序)。因此,.sorted()
必须遍历所有元素才能产生排序流,这允许findFirst()
终端操作返回排序流的第一个元素。结果,peek
在所有元素上执行,即使终端操作只需要第一个元素。
推荐阅读
- excel - MINIFS、MAXIFS 等公式标准中的转义运算符 <,>,=
- c++ - Cryptopp 制作 ARM 32 位共享库
- python - TypeError:“模块”对象不可调用。我尝试了各种解决方案,但到目前为止没有任何效果
- firebase - 无法从方法“_userFromFirebaseUser”返回“Null”类型的值,因为它的返回类型为“User”
- python-3.x - 如何优化这个 python 脚本 Pandas 的时间?
- r - Ggplot2:不在饼图标签中显示 0 值
- angular - devextreme angular - 设置 DxDataGrid 自定义 headerFilter 的初始过滤器值
- python - Python变量没有被增加
- reactjs - 反应 onDrop 事件与法语字符冲突
- c# - Ninject 依赖注入 - 两个具体类