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 有什么区别?
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01