带条件的嵌套循环的Java Lambda表达式

带条件的嵌套循环的Java Lambda表达式,java,lambda,java-8,nested-loops,Java,Lambda,Java 8,Nested Loops,我不熟悉lambda表达式,并尝试使用它们将以下代码简化为lambda等效代码。我已经研究了reduce、flatMap和forEach,以及其他一些东西,但我显然遗漏了一些东西,因为我尝试的所有东西要么在语法上不正确,要么我没有我需要的参考 我需要针对集合中的所有其他元素对每个元素执行分析。我将其编码为带有条件的嵌套循环。一旦识别出不匹配的元素,将使用这两个元素进行计算。最后,我希望为每个比较计算收集结果 下面是原始代码: final List<Element> updated =

我不熟悉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);
}
显然,这是错误的,因为我没有对second的引用,也没有second不等于first的条件/过滤器

如何通过有条件地将集合返回到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()));

这很困难,因为您的
newAttribute=newAttribute.add(…)
更新不可并行化。如果您可以聚合所有
computeChange
结果,然后从该聚合中创建一个
属性
(或
元素
),那么这将更容易。我会保持原样。
computeChange
返回什么?一个
元素
属性
,或者一个数字?不是100%确定,但我认为您试图做的是不可能的,至少在并行流中是不可能的。当您试图累积属性和元素时,您必须使用带有三个参数的
reduce
,但随后需要一个组合器来组合不同并行流的结果,将两个属性组合为一个新属性。那么:如何组合两个属性呢?computeChange返回一个属性我不认为这是
.foreach(newAttribute::add)
将起作用,因为
add
似乎创建了一个新属性。不过,
reduce
可能会起作用。@tobias\k foreach报告错误:类型流的foreach(属性::add)方法未定义。使用reduce可消除error.pgerstoft、@tobias_k我需要将foreach/reduce的参数更改为be属性:add,否则我收到错误“type属性未定义此处适用的add(Attribute,Attribute)”。但是,我没有通过单元测试,因此我认为重复的更新/添加不能正常工作。我会继续戳它,但如果你有任何建议,我很乐意听到。因此,使用foreach似乎会产生误导性错误,但foreach允许pgerstoft提供的论点。然而,它并没有产生预期的结果。我还在找。@pgerstoff它几乎成功了,但似乎出现了一个一个接一个的错误。谢谢你的帮助。当我按照如下方式更新代码时,我让它工作:elements.stream().map(first->{Attribute zero=new Attribute();Attribute newAttribute=elements.stream().filter(second->first!=second).map(second->computeChange(first,second)).reduce(zero,(a,b)->a.add(b));返回新元素(first.getEntry(),first.getAttribute().add(newAttribute),first.getValue();}).collect(Collectors.toList())
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()));