Stream ordered/unordered problems

后端 未结 2 2037
情话喂你
情话喂你 2020-12-09 12:20

I have the following code:

Set l = new TreeSet<>();
l.add(1);
l.add(10);
l.add(3);
l.add(-3);
l.add(-4);

and I want to

2条回答
  •  孤街浪徒
    2020-12-09 13:05

    The unordered() operation doesn't do any actions to explicitly unorder the stream. What it does is that it removes the constraint on the stream that it must remain ordered, thereby allowing subsequent operations to use optimizations that don't have to take ordering into consideration.

    You can read about this in the Java 8 docs:

    For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.
    For parallel streams, relaxing the ordering constraint can sometimes enable more efficient execution.

    ...

    In cases where the stream has an encounter order, but the user does not particularly care about that encounter order, explicitly de-ordering the stream with unordered() may improve parallel performance for some stateful or terminal operations.

提交回复
热议问题