OneBite.Dev - Coding blog in a bite size

find the unique elements in two arrays in java

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

  int[] arr1 = {1, 2, 3, 4, 5}; 
  int[] arr2 = {3, 4, 6, 7, 8}; 
  
  Set<Integer> set = new HashSet<>();
  
  // Loop through the first array and add each element to the set 
  for (int x : arr1) 
    set.add(x); 
  
  // Loop through the second array and check if the element is present in the set  
  for (int x : arr2) { 
    if (set.contains(x)) 
      set.remove(x); 
  } 
  
  // Print the union of arr1 and arr2 
  for (int x : set) 
    System.out.print(x + " "); 

This code is used to get the unique elements from two arrays. Firstly, it creates a set to store the elements. Then it loops through both of the arrays and adds/removes elements depending on if they are found in both arrays. After the loop, it prints out the remaining elements that were only found in one of the arrays. The elements in the set will automatically be unique so that duplicates are eliminated.

java