Check if an ArrayList contains every element from another ArrayList (or Collection)
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
Solution 1:
There is a method called containsAll
declared in the java.util.Collection
interface. In your setting one.containsAll(two)
gives the desired answer.
Solution 2:
Per the List interface:
myList.containsAll(...);
Solution 3:
Take a look at containsAll(Collection<?> c)
method from List
interface. I think it is what you are looking for.
Solution 4:
Here is another example use of containsAll() that I have used for asserting that two arrays are equal in JUnit testing:
List<String> expected = new ArrayList<String>();
expected.add("this");
expected.add("that");
expected.add("another");
List<String> actual = new ArrayListString();
actual.add("another");
actual.add("that");
actual.add("this");
Assert.assertTrue("The lists do not match!", expected.containsAll(actual));
Solution 5:
You can use containsAll
method of the list to do the check. However, this is a linear operation. If the list is large, you should convert it to HashSet
first, and then perform containsAll
:
HashSet tmp = new HashSet(one);
if (tmp.containsAll(two)) {
...
}
If the length of one
is N
and the length of two is M
, this solution has time complexity of O(M+N)
; the "plain" containsAll
has the complexity of O(M*N)
, which may be significantly worse.