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
Take a look at
containsAll(Collection<?> c)
method fromList
interface. I think it is what you are looking for.Per the List interface:
Here is another example use of containsAll() that I have used for asserting that two arrays are equal in JUnit testing:
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 toHashSet
first, and then performcontainsAll
:If the length of
one
isN
and the length of two isM
, this solution has time complexity ofO(M+N)
; the "plain"containsAll
has the complexity ofO(M*N)
, which may be significantly worse.There is a method called
containsAll
declared in thejava.util.Collection
interface. In your settingone.containsAll(two)
gives the desired answer.Your code in the example doesn't make sense, but here's an example anyway.
It simply loops through all of
two
's elements and checks to see if they are inone
.Then the boolean
good
contains the value you want.See ArrayList#contains.
EDIT: oh wow, I totally forgot containsAll. Oh well, this is an alternate way to do it if you really want to understand it.