OneBite.Dev - Coding blog in a bite size

find the common elements in two arrays in java

Code snippet on how to find the common elements in two arrays in java

  public static int[] findCommonElements(int[] arr1, int[] arr2){  
    // Create an empty array to store the common elements
    int[] commonElements = new int[arr1.length];  
    // Initialize the index to 0
    int k = 0;  
    // Iterate over both arrays  
    for (int i=0;i<arr1.length;i++){  
      for (int j=0;j<arr2.length;j++){  
        // Check if both arrays have the same element
        if(arr1[i] == arr2[j]){  
          // add the element to the commonElements array
          commonElements[k] = arr1[i];  
          // Increase the index
          k++;  
        }  
      }  
    }  
    return commonElements;  
  }  

This code snippet finds the common elements of two arrays. First, the code creates an empty array with the same length as the first array. This will be used to store the common elements. Next, it initializes a counter k to keep track of the index of the common element array. Then it starts two loop; one loop to iterate over the first array, and a nested loop to iterate over the second array. In each iteration, it checks if the current element of the first array is the same as the current element of the second array. If they are the same, it adds the element to the commonElements array and increases the index. At the end, it returns the commonElements array.

java