Tod*_*odd 11 java lambda nested-loops java-8
我是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);
}
Run Code Online (Sandbox Code Playgroud)
然后,我尝试了lambda表达式的许多变体,其中最简单的是:
elements.parallelStream()
.map(first -> new Element(first.getEntry(), first.getAttribute().add(
computeChange(first, second)), first
.getValue())).collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)
显然,这是错误的,因为没有第二个可用的参考,没有条件/过滤器第二个不等于第一个.
如何通过条件将集合返回到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()));
Run Code Online (Sandbox Code Playgroud)