for (int i = 0; i < arrayA.length; i++) {
for (int y = 0; y < arrayB.length; y++) {
if (arrayA[i] == arrayB[y]) {
cnt++;
}
}
}
if (cnt == arrayB.length) {
// B is subset of A
}
Asked
Active
Viewed 70 times
-4

Andy Turner
- 137,514
- 11
- 162
- 243

Rei Koleci
- 11
- 2
1 Answers
1
You can convert arrays into lists
and use containsAll
method to check this, e.g.:
List<String> list1 = Arrays.asList(a);
List<String> list2 = Arrays.asList(b);
list1.containsAll(list2);
Here's javadoc for containsAll
method.
Update
Here's how it will work in case of int
arrays:
int[] a = new int[10];
int[] b = new int[10];
List<Integer> list1 = Arrays.stream(a).boxed().collect(Collectors.toList());
List<Integer> list2 = Arrays.stream(b).boxed().collect(Collectors.toList());
list1.containsAll(list2);

Darshan Mehta
- 30,102
- 11
- 68
- 102
-
What if it is array if primitive type like `int[]`? It is worth mentioning that `Arrays.asList` will not handle this case correctly and we will need other way to fill our Lists. – Pshemo Feb 26 '17 at 14:22
-
Based on array type, we can change the collection type accordingly. If it's primitive, we can even use `stream` and box it. – Darshan Mehta Feb 26 '17 at 14:23
-
That is very true. IMO It is worth putting it in answer. – Pshemo Feb 26 '17 at 14:24
-
Updated the answer, thanks for pointing it out :) – Darshan Mehta Feb 26 '17 at 14:28
-
Another aspect worth mentioning is that for situation like `{1}.containsAll{1,1}` (where `{x}` represents list with `x` elements) will get as response `true`. `containsAll` simply checks if each element from tested collection exist in original collection (here each `1` exist in original collection `{1}`). So it doesn't care about number of elements, but about their equality. – Pshemo Feb 26 '17 at 14:49