=?gb2312?B?tPC4tDogZm9yRWFjaE9yZGVyZWQncyBzZW1hbnRpYw==?=
Tristan Yan
tristan.yan at oracle.com
Fri Jun 14 21:21:31 PDT 2013
"If the stream source is unordered then this degenerates to the same as the regular unordered forEach" - Does it mean we can't guarantee same order even we do forEachOrder in stream which source is unordered?
-----邮件原件-----
发件人: Brian Goetz
发送时间: Saturday, June 15, 2013 2:14 AM
收件人: Tristan Yan
抄送: lambda-dev at openjdk.java.net
主题: Re: forEachOrdered's semantic
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