Java 带条件的嵌套循环的 Lambda 表达式
Java Lambda Expression for Nested Loops with Conditional
我是 lambda 表达式的新手,正在尝试使用它们将以下代码简化为 lambda 等效项。我已经研究了 reduce 和 flatMap 以及 forEach 以及其他一些东西,但我显然遗漏了一些东西,因为我尝试的所有东西要么在语法上不正确,要么我没有我需要的参考。
我需要针对集合中的所有其他元素对每个元素进行分析。我将其编码为带有条件的嵌套循环。一旦识别出不匹配的元素,就会使用这两个元素进行计算。最后,我想要每个比较计算的结果集合。
所以,这是原始代码:
final List<Element> updated = new ArrayList<>(elements.size());
for (final Element first : elements) {
Attribute newAttribute = first.getAttribute();
for (final Element second : elements) {
if (!first.equals(second)) {
newAttribute = newAttribute.add(computeChange(first, second));
}
}
final Element newElement = new Element(first.getEntry(), newAttribute, first.getValue());
updated.add(newElement);
}
然后,我尝试了很多lambda表达式的变体,其中最简单的是:
elements.parallelStream()
.map(first -> new Element(first.getEntry(), first.getAttribute().add(
computeChange(first, second)), first
.getValue())).collect(Collectors.toList()));
显然,这是错误的,因为我没有可用的第二个参考,也没有 condition/filter 第二个不等于第一个。
如何通过有条件地将集合返回到 lambda 表达式来减少这个嵌套循环?
非常感谢任何帮助。
尝试:
elements.stream()
.map(first -> {
Attribute newAttribute = elements.stream().filter(second -> !first.equals(second))
.map(second -> computeChange(first, second))
.reduce(first.getAttribute(), (a, b) -> a.add(b))
return new Element(first.getEntry(), newAttribute, first.getValue());
}).collect(Collectors.toList()));
我是 lambda 表达式的新手,正在尝试使用它们将以下代码简化为 lambda 等效项。我已经研究了 reduce 和 flatMap 以及 forEach 以及其他一些东西,但我显然遗漏了一些东西,因为我尝试的所有东西要么在语法上不正确,要么我没有我需要的参考。
我需要针对集合中的所有其他元素对每个元素进行分析。我将其编码为带有条件的嵌套循环。一旦识别出不匹配的元素,就会使用这两个元素进行计算。最后,我想要每个比较计算的结果集合。
所以,这是原始代码:
final List<Element> updated = new ArrayList<>(elements.size());
for (final Element first : elements) {
Attribute newAttribute = first.getAttribute();
for (final Element second : elements) {
if (!first.equals(second)) {
newAttribute = newAttribute.add(computeChange(first, second));
}
}
final Element newElement = new Element(first.getEntry(), newAttribute, first.getValue());
updated.add(newElement);
}
然后,我尝试了很多lambda表达式的变体,其中最简单的是:
elements.parallelStream()
.map(first -> new Element(first.getEntry(), first.getAttribute().add(
computeChange(first, second)), first
.getValue())).collect(Collectors.toList()));
显然,这是错误的,因为我没有可用的第二个参考,也没有 condition/filter 第二个不等于第一个。
如何通过有条件地将集合返回到 lambda 表达式来减少这个嵌套循环?
非常感谢任何帮助。
尝试:
elements.stream()
.map(first -> {
Attribute newAttribute = elements.stream().filter(second -> !first.equals(second))
.map(second -> computeChange(first, second))
.reduce(first.getAttribute(), (a, b) -> a.add(b))
return new Element(first.getEntry(), newAttribute, first.getValue());
}).collect(Collectors.toList()));