OneBite.Dev - Coding blog in a bite size

find the union of two arrays in java

Code snippet on how to find the union of two arrays in java

  int[] a = {1, 2, 3, 4, 5};
  int[] b = {4, 5, 6, 7};
  
  int[] c = new int[a.length + b.length];
  
  int i = 0;
  for (final int element : a) {
    c[i] = element;
    i++;
  }
  
  for (final int element : b) {
    c[i] = element;
    i++;
  }

This code finds the union of two given arrays, a and b. First, an array c of length of the two arrays combined is declared. Then, the elements of array a are iterated through and added to array c. Once all elements from array a are added, the elements of array b are iterated through and added to array c, thereby giving the union of array a and array b. Finally, the union of two arrays is stored in array c.

java