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 有什么区别?
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01