Check if one list contains element from the other Check if one list contains element from the other java java

Check if one list contains element from the other


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.


You can use Apache Commons CollectionUtils:

if(CollectionUtils.containsAny(list1,list2)) {      // do whatever you want} else {     // do other thing }  

This assumes that you have properly overloaded the equals functionality for your custom objects.


To shorten Narendra's logic, you can use this:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element));