Home > Blockchain >  How to compare two lists of custom objects for some properties using streams in Java?
How to compare two lists of custom objects for some properties using streams in Java?

Time:01-06

What is the best way to compares the items of two lists by (only) some of their properties?

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(...);

I tried

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

...but this doesn't work.

It would be sufficient to find any/the first match and return true then or false if no match can be found.

CodePudding user response:

If you want both properties to match, it should be:

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

This will compare all pairs of elements of the two lists until a match is found.

  •  Tags:  
  • Related