Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

关于java8 Stream中ordered Stream和unordered Stream的问题

我对于stream api中所描述的ordered stream 和 unordered stream有迷惑。
根据api的描述,两者的核心区别应该在于是否有encounter order

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as `List` or arrays) are intrinsically ordered, whereas others (such as `HashSet`) are not. Some intermediate operations, such as `sorted()`, may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered, such as BaseStream.unordered(). Further, some terminal operations may ignore encounter order, such as `forEach()`.

我的理解是:
List 和 Array生成的stream都是ordered stream,而使用 BaseStream.unordered() 方法则可以去除 encounter order 这个约束,变为 unordered stream。
HashSet 生成的stream是unordered stream,可以通过排序方法 sort() 强行给stream添加一个 encounter order的约束,变为 ordered stream。

我在此理解的基础上,对于 findFirst() 方法进行了尝试
以下是findFirst()方法的描述

Optional<[T]>?findFirst()

Returns an Optional describing the first element of this stream, 
or an empty Optional if the stream is empty. 
If the stream has no encounter order, then any element may be returned.

根据此方法描述,如果stream没有encounter order 的话,就可能会随意返回流中的一个值。

我创建了一个ArrayList,并调用了unordered()方法变成了unordered stream, 这样的话 findFirst()方法应该会随机返回ArrayList中的一个值。
但是我将下列代码循环了10000次,每次findFirst都是1。

    @Test
    void t5() {
        for (int i = 0; i < 10000; i++) {
            List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
            Optional<Integer> first = list.stream().unordered().findFirst();
            assertEquals(1, first.get(), String.format("findFirst()->%s,loop->%s", first.get(), i));
        }
    }

这段代码我执行了很多次,结果都没变。是我的测试代码有问题还是我的理解有问题,希望各位大佬能帮忙解答。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

unordered并不会打乱顺序,只是解除限制,不再保证顺序,然后某些操作可以做一些特殊优化
是“不保证有序”,不是“保证无序“
想打乱的话,加个.parallel()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...