Search code examples
javalistfindelement

Check if one list contains element from the other


I have two lists with different objects in them.

List<Object1> list1;
List<Object2> list2;

I want to check if element from list1 exists in list2, based on specific attribute (Object1 and Object2 have (among others), one mutual attribute (with type Long), named attributeSame).

right now, I do it like this:

boolean found = false;
for(Object1 object1 : list1){
   for(Object2 object2: list2){
       if(object1.getAttributeSame() == object2.getAttributeSame()){
           found = true;
           //also do something
       }
    }
    if(!found){
        //do something
    }
    found = false;
}

But I think there is a better and faster way to do this :) Can someone propose it?

Thanks!


Solution

  • If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

    !Collections.disjoint(list1, list2);
    

    If you need to test a specific property, that's harder. I would recommend, by default,

    list1.stream()
       .map(Object1::getProperty)
       .anyMatch(
         list2.stream()
           .map(Object2::getProperty)
           .collect(toSet())
           ::contains)
    

    ...which collects the distinct values in list2 and tests each value in list1 for presence.