Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if an array contains all elements in another array

Tags:

java

arrays

I am trying to loop through 2 arrays, the outer array is longer then the other. It will loop through the first and if the 2nd array does not contain that int it will return a false. But I cannot figure out how to go about this. This is what I have so far:

public boolean linearIn(int[] outer, int[] inner) {
  for (int i = 0; i < outer.length; i++) {
    if (!inner.contains(outer[i])) {
      return false;
    }
  }

  return true;
}

I am getting this error when run:

Cannot invoke contains(int) on the array type int[]

I am wondering if it can be done without using a nested loop (like above). I know I'm doing something wrong and if anyone could help on the matter it would be great. Also I wasn't sure what class to look for in the java doc for the int[].

like image 717
Caveman42 Avatar asked May 13 '13 14:05

Caveman42


People also ask

How do you check if an array contains all the elements of another array?

Method 3: Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you find an array within an array?

Use forEach() to find an element in an array The Array.

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.


1 Answers

You could check that the larger of the arrays outer contains every element in the smaller one, i.e. inner:

public static boolean linearIn(Integer[] outer, Integer[] inner) {

   return Arrays.asList(outer).containsAll(Arrays.asList(inner));
}

Note: Integer types are required for this approach to work. If primitives are used, then Arrays.asList will return a List containing a single element of type int[]. In that case, invoking containsAll will not check the actual content of the arrays but rather compare the primitive int array Object references.

like image 161
Reimeus Avatar answered Oct 22 '22 16:10

Reimeus