本文介绍了Java流的处理顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

LinkedList<Integer> ints = new LinkedList();
//fill it with some ints
Stream<Integer> stream = ints.stream();
//process the stream in some way

我的问题是,是否可以保证流的处理顺序与基础LinkedList相同?我阅读了文档,但是没有有关订购的任何信息.

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.

推荐答案

来自文档:

如果订购了流,则大多数操作都被限制为只能在以下位置进行操作 遇到顺序中的元素;如果流的来源是 包含[1、2、3]的列表,然后是执行map(x-> x * 2)的结果 必须为[2,4,6].但是,如果源没有定义的相遇 顺序,则值[2、4、6]的任何排列都是有效的 结果.

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:

最好的方法是避免流传输有状态的行为参数 完全运作;通常有一种重组流的方法 避免状态的管道.

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.

另请参阅以下问题的答案:如何确保java8流中的处理顺序?

See also the answer to this question: How to ensure order of processing in java8 streams?

简而言之,如果您使用顺序流(在一个线程中执行的流),并且您对诸如forEach()之类的操作很谨慎,则看起来可以保留顺序.但是,这可能不是一个好主意.

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.

这篇关于Java流的处理顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:31