Stream.of 和 IntStream.range 有什么区别?有什么区别、of、Stream、range

2023-09-07 09:54:51 作者:范二姑娘不伤感

请考虑以下代码:

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.

 
精彩推荐
图片推荐