Stream.of 和 IntStream.range 有什么区别? [英] What is the difference between Stream.of and IntStream.range?

查看:24
本文介绍了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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆