如何使用 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());}
));

...但这不起作用。

找到 any/the 第一个匹配项就足够了,如果找不到匹配项,则 return 为真,否则为假。

更新/示例


A a1 = new A();
a1.setType("AB");
a1.setValue("xx");

A a2 = new A();
a2.setType("XY");
a2.setValue("00");

List<A> listA = List.of(a1, a2);

A b1 = new A();
b1.setType("AB");
b1.setValue("xx");

A b2 = new A();
b2.setType("XY");
b2.setValue("");

List<A> listB = List.of(b1, b2);

在(compVal = listAexpVal = listB 中使用这些列表):

public static boolean isValid(final List<A> compAs, final List<A> expAs) {
    
    return compAs.stream().anyMatch(a -> expAs.stream().anyMatch(e -> {
    return c.getType().equals(e.getType()) &&
                c.getValue().equals(e.getValue())
    }
} 

assertFalse(isValid()) 测试失败(returns truefalse 是预期的)。

我试过

return e.equals(c)

还有。

如果列表确实相等,则使用 allMatch() 会失败。

如果您希望两个属性都匹配,应该是:

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

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

编辑:

如果您要求第一个 List 的每个元素都具有第二个 List 的匹配元素,请在外部 Stream:[=16] 中使用 allMatch =]

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