我有一个包含 A、B、C 的列表
。
C reduce A reduce B != A reduce B reduce C
(但是,A reduce (B reduce C) 可以)。
换句话说,我的归约运算是结合性的而不是交换性的。
java 是否强制有序顺序流(例如列表中的默认流)减少总是根据遇到顺序发生?也就是说,java 会重新排序归约(例如 B 归约 A 而不是 A 归约 B)吗?
(希望这足够清楚)。
编辑添加一个小演示,可能有助于澄清
Stream.of(" cats ", " eat ", " bats ")
.reduce("", (a, b) -> a + b); // cats eat bats
有了上面的内容,输出会是“ bat 猫吃”或“吃 bat 猫”吗?这在规范中的某处得到保证吗?
最佳答案
根据规范,它尊重元素的顺序。
证明很简单。 specification声称缩减函数必须 关联。
但是,如果不保留顺序,关联性 本身就没有任何意义。根据mathematical definition关联属性:
Within an expression containing two or more occurrences in a row of the same associative operator, the order in which the operations are performed does not matter as long as the sequence of the operands is not changed.
换句话说,关联属性并不意味着:
(a + b) + c = (a + c) + b
它只允许任意排列操作的应用顺序。
关于java - 有序流的减少是否按顺序减少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49520234/