繁体   English   中英

如何使用 Java 中的流比较某些属性的两个自定义对象列表?

[英]How to compare two lists of custom objects for some properties using streams in Java?

通过(仅)某些属性比较两个列表的项目的最佳方法是什么?

public class A {
    private String type;
    private String value;
    private String foo;
    private String bar;
}

List<A> listA = List.of(...);
List<A> listB = List.of(...);

我试过了

return listA.stream().anyMatch( a -> listB.stream().anyMatch(b -> {
    a.getType().equals(b.getType());
    a.getValue().equals(b.getValue());}
));

...但这不起作用。

找到任何/第一个匹配项并返回 true then 或 false 如果找不到匹配项就足够了。

如果您希望两个属性匹配,则应为:

return listA.stream()
            .anyMatch( a -> listB.stream()
                                 .anyMatch(b -> a.getType().equals(b.getType()) &&
                                                a.getValue().equals(b.getValue())));

这将比较两个列表的所有元素对,直到找到匹配项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM