java stream 有序,Java流的处理顺序

I have the following:

LinkedList ints = new LinkedList();

//fill it with some ints

Stream stream = ints.stream();

//process the stream in some way

My question is if it's guaranteed that the order of processing of the stream is as of the underlying LinkedList? I read the documentation but there was no any info about the ordering.

In my case it's critically to preserve the 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().

If a stream is ordered, most operations are constrained to operate on

the elements in their encounter order; if the source of a stream is a

List containing [1, 2, 3], then the result of executing map(x -> x*2)

must be [2, 4, 6]. However, if the source has no defined encounter

order, then any permutation of the values [2, 4, 6] would be a valid

result.

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...

Also, as you mentioned that processing order matters for you see here:

Stream pipeline results may be nondeterministic or incorrect if the

behavioral parameters to the stream operations are stateful...

The best approach is to avoid stateful behavioral parameters to stream

operations entirely; there is usually a way to restructure the stream

pipeline to avoid statefulness.

In short, it looks like you can preserve the order, if you use sequential streams (streams that are executed in one thread) and if you are careful with operations like forEach(). However it probably is not a good idea.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值