首页 > 解决方案 > 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("\n#2");
IntStream.range(0, 4)
        .peek(e -> System.out.println(e))
        .sorted()
        .findFirst();

输出将是:

#1
0
1
2
3

#2
0

谁能解释一下,为什么两个流的输出不同?

标签: javajava-stream

解决方案


好吧,IntStream.range()返回a sequential ordered IntStream from startInclusive(inclusive) to endExclusive (exclusive) by an incremental step of 1,这意味着它已经排序。.sorted()由于它已经排序,因此以下中间操作什么都不做是有道理的。结果,peek()仅在第一个元素上执行(因为终端操作只需要第一个元素)。

另一方面,传递给的元素Stream.of()不一定是排序的(并且该of()方法不检查它们是否已排序)。因此,.sorted()必须遍历所有元素才能产生排序流,这允许findFirst()终端操作返回排序流的第一个元素。结果,peek在所有元素上执行,即使终端操作只需要第一个元素。


推荐阅读