forEachOrdered's semantic

Brian Goetz brian.goetz at oracle.com
Fri Jun 14 11:13:42 PDT 2013


There is a difference between *ordered* and *sorted*.

Ordered means "has a defined encounter order".  Indexed aggregates 
(Lists, arrays), queues, and sorted collections all have a defined 
encounter order; hash-based collections (e.g., HashSet) do not.

Sorted implies ordered, but it further implies a specific order.

Whether a stream is ordered or not is important, because there are 
optimizations that are legal only for unordered streams, which are 
relevant for parallel executions.  This is why there are two versions of 
forEach.  The normal version of forEach is not constrained to the 
encounter order, but instead delivers elements to the consumer as they 
are ready.  (This is sometimes called the *temporal order*.)  Most of 
the time this is what people want when they do forEach on a parallel 
stream.  But if they really want the elements in their encounter order, 
you can use forEachOrdered.  This is likely identical to forEach for 
sequential traversals, but likely slower than forEach for parallel 
traversals.  However, you still may be able to get some parallelism 
benefit anyway, such as in cases like

   stream.parallel()
         .filter(veryExpensiveFn)
         .forEachOrdered(...)

This at least lets the expensive operation be parallelized, and then the 
elements are delivered in left-to-right order.  (If the stream source is 
unordered then this degenerates to the same as the regular unordered 
forEach.)

On 6/14/2013 12:33 PM, Tristan Yan wrote:
>>From other thread and spec Stream.forEachOrdered() should behave like an order iteration but latest code shows it is not sorted. Below code shows result as
>
> 10 9 3 2 7 4 6 1 5 8
>
> This is the same output as forEach, is there anything wrong?
>
>          List<Integer> oneToTen = IntStream.range(1, 11).boxed()
>
>                  .collect(Collectors.<Integer>toList());
>
>          Collections.shuffle(oneToTen);
>
>          oneToTen.stream().forEachOrdered(t -> {
>
>              System.out.print(t);
>
>              System.out.print(" ");
>
>        });
>
>
>
> Tristan Yan(Haibo Yan)
>
> Office : 8610-61066212
>
> Fax  : 8610-61065441
>
> Cell  : 86-18610696822
>
>
>
> 2F, Building No. 24, Zhongguancun Software Park
>
> Haidian District HYPERLINK "http://people.us.oracle.com/pls/oracle/f?p=8000:6:396067987304343:::6:P6_CITY:Beijing"Beijing , 100193
>
> oracle
>
>
>
>
>
>


More information about the lambda-dev mailing list