Check if an ArrayList contains every element from another ArrayList (or Collection)

Evorlor picture Evorlor · Jan 24, 2013 · Viewed 96.9k times · Source

There is probably a simple one-liner that I am just not finding here, but this is my question:

How do I check if an ArrayList contains all of the objects in another ArrayList? I am looking (if it exists) for something along the lines of:

//INCORRECT EXAMPLE:
if(one.contains(two))
{
    return true;
}
else
{
    return false;
}

For example:

ArrayList one = {1, 2, 3, 4, 5}

ArrayList two = {1, 2, 3} --> True
ArrayList two = {} --> True
ArrayList two = {1, 2, 3, 4, 5} --> True
ArrayList two = {1, 5, 2} --> True
ArrayList two = {1, 7, 4} --> False
ArrayList two = {0, 1, 3} --> False
ArrayList two = {4, 5, 6} --> False
ArrayList two = {7, 8, 9} --> False

Answer

C-Otto picture C-Otto · Jan 24, 2013

There is a method called containsAll declared in the java.util.Collection interface. In your setting one.containsAll(two) gives the desired answer.