我是 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()));
显然,这是错误的,因为我没有可用的第二个引用,也没有第二个不等于第一个的条件/过滤器。
如何通过有条件地将集合返回到 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()));
关于具有条件的嵌套循环的 Java Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928750/