Comparing if two lists have the same elements based on a property

You can check listA‘s all element exists in listB

boolean isSame = listA.stream()
                      .allMatch(a -> listB.stream()
                                          .anyMatch(b -> b.getCode().equals(a.getCode())));

You can create a set of code from a list and check contains in O(1)

Set<String> set = listB.stream().map(e -> e.getCode()).collect(Collectors.toSet());

Then you can find in set for every list element

boolean isSame = listA.stream().allMatch(a -> set.contains(a.getCode()));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top