javaspringjava-streamapache-commons

How to filter a List with objects of two different classes and compare them by fields?


I have two different lists. I want to find and filter by field not on the other list. For example.

List<ObjectOne>      List<ObjectTwo>
field | value        field | value
{id=5, name="aaa"}   {xId=4, text="aaa"}
{id=6, name="bbb"}   {xId=6, text="bbb"}
{id=7, name="ccc"}   {xId=5, text="ccc"}

If I want to filter one list, I am using org.springframework.cglib.core.CollectionUtils like this:

CollectionUtils.filter(objectOne, s -> (
(ObjectOne) s).getId() == anyObject.getXId()
&&  (ObjectOne) s).getName() == anyObject.getText());

But I want to compare two Lists, and I want to find noncontains value like this:

objectOne = {id=5, name="aaa"} , {id=7, name="ccc"}

How can I filter with the Java Stream API or any third-party libraries?


Solution

  • noneMatch helps you here.

    objectOnes.stream()
              .filter(x -> objectTwos.stream()
                                     .noneMatch(y -> y.text.equals(x.name) && y.xId == x.id))
              .collect(Collectors.toList());