gpt4 book ai didi

java - Java 的 ArrayList.stream().anyMatch() 是否保证顺序处理?

转载 作者:搜寻专家 更新时间:2023-11-01 02:04:20 26 4
gpt4 key购买 nike

我有这个代码:

ArrayList<Detector> detectors;
detectors.stream().anyMatch(d -> d.detectRead(impendingInstruction, fieldName));

但我也想保证:

  • 列表按顺序处理,从第一个元素到最后一个;
  • 一旦元素返回 true,计算立即停止

这是否总是正确的,或者如果不是,是否至少对于所有常见的 JDK 实现都是如此?

最佳答案

你的问题暗示了对流操作的副作用的担忧,否则你不会关心顺序或立即终止。来自Javadoc :

Side-effects

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

If the behavioral parameters do have side-effects, unless explicitly stated, there are no guarantees as to the visibility of those side-effects to other threads, nor are there any guarantees that different operations on the "same" element within the same stream pipeline are executed in the same thread. Further, the ordering of those effects may be surprising. Even when a pipeline is constrained to produce a result that is consistent with the encounter order of the stream source (for example, IntStream.range(0,5).parallel().map(x -> x*2).toArray() must produce [0, 2, 4, 6, 8]), no guarantees are made as to the order in which the mapper function is applied to individual elements, or in what thread any behavioral parameter is executed for a given element.

所以契约(Contract)似乎是您可能会逃脱惩罚,但它不能保证工作。

关于java - Java 的 ArrayList.stream().anyMatch() 是否保证顺序处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com