# java – Remove duplicates in the union of two array's

## Question:

I have a problem finding the solution to this exercise, if you can help me, I would really appreciate it.

They pass me two array's of integers and I must return another one with the mixture of both, ignoring the repeated ones.

For example if the array1 contains these numbers `{1,2,3,4,5,5,4}` and the array2 these `{1,7,8,3,5}` the result of the mixture would be this: `{2,4,7,8}` .

I have managed to eliminate the repeated ones, but if one of the numbers appears in the array's, it only deletes one.

My code is the following:

``````public class InicioArray {
public static void main(String[] args) {
int a[]= {4,8,2,9,21,5,13,16};
int c[]= {21,16,14,8,12,16,7,22};

//System.out.println(Arrays.toString(a));
int b[]=Arrays2.sinRepeticion(a,c);
System.out.println(Arrays.toString(b));
}
}
``````

``````import java.util.Arrays;

public class Arrays2{
// reduce el array al nuevo tamaño
// No modifica el array pasado como parámetro
public static int[] sinRepeticion(int[] array, int[] array2) {
int aux[]=Arrays.copyOf(array, array.length);
int aux2[]=Arrays.copyOf(array2, array2.length);
int res[]=new int[array.length+array2.length];
int aux3[]=new int [res.length];
for (int i = 0; i < aux3.length / 2; i++) {
aux3[i * 2] = aux[i];
aux3[i * 2 + 1] = aux2[i];
}

Arrays.sort(aux3);
Arrays.sort(aux2);
Integer valor=aux3;
int j=0;

for (int i=0;i<aux3.length;i++)

if (valor!=aux3[i]) {
res[j++]=valor;
valor=aux3[i];
}

res[j++]=valor;

aux3=Arrays.copyOf(res,j);

return aux3;
}
}
``````

First we create an array whose size is going to be equal to the sum of the sizes of the original arrays

``````int tam = arregloA.length + arregloB.length;
int[] ArregloC= new int[tam];
``````

We then fill this new array with the elements of the original arrays

In order not to complicate ourselves so much, we first make a cycle that copies each element of arrayA into the new array and then we make another cycle that copies the elements of arrayB into the new array. This step can of course be further optimized.

``````int indice = 0;

for(int i=0;i<arregloA.length;i++)
{
arregloC[indice] = arregloA[i];
indice++;
}

for(int i=0;i<ArregloB.length;i++)
{
arregloC[indice] = arregloB[i];
indice++;
}
``````

We already have all the elements of the two original arrays copied into the new array, now we proceed to eliminate the duplicates

For that we use the HashSet data structure which, when receiving a list, automatically eliminates duplicates

``````Set<Integer> NoDuplicados = new HashSet<Integer>(Arrays.asList(arregloC));
``````
Scroll to Top