What is the difference between Stream.of and IntStream.range?(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("
#2");
IntStream.range(0, 4)
.peek(e -> System.out.println(e))
.sorted()
.findFirst();
输出将是:
#1
0
1
2
3
#2
0
谁能解释一下,为什么两个流的输出不同?
Could anyone explain, why output of two streams are different?
推荐答案
嗯,IntStream.range()
返回一个从startInclusive(inclusive)到endExclusive(exclusive)的有序IntStream增量步 1
,这意味着它已经排序.由于它已经排序,因此下面的 .sorted()
中间操作什么都不做是有意义的.结果,peek()
只在第一个元素上执行(因为终端操作只需要第一个元素).
Well, IntStream.range()
returns a sequential ordered IntStream from startInclusive(inclusive) to endExclusive (exclusive) by an incremental step of 1
, which means it's already sorted. Since it's already sorted, it makes sense that the following .sorted()
intermediate operation does nothing. As a result, peek()
is executed on just the first element (since the terminal operation only requires the first element).
另一方面,传递给 Stream.of()
的元素不一定是排序的(并且 of()
方法不会检查它们是否已排序).因此,.sorted()
必须遍历所有元素才能产生排序流,这允许 findFirst()
终端操作返回排序流的第一个元素.结果,peek
对所有元素执行,即使终端操作只需要第一个元素.
On the other hand, the elements passed to Stream.of()
are not necessarily sorted (and the of()
method doesn't check if they are sorted). Therefore, .sorted()
must traverse all the elements in order to produce a sorted stream, which allows the findFirst()
terminal operation to return the first element of the sorted stream. As a result, peek
is executed on all the elements, even though the terminal operation only needs the first element.
这篇关于Stream.of 和 IntStream.range 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Stream.of 和 IntStream.range 有什么区别?


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01