Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one list contains element from the other

People also ask

How do you check if a list contains items from another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you check if a list contains elements from another list in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if an item of a list is in another list Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.

Can I check if a list contains any item from another list C#?

You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.


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

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);