The following program demonstrates how to Remove Duplicates from an Array in Java.
In this program, first, we initialise the array with numbers. Also, there are enough duplicates in the array initially. In order to remove the duplicates, we use another array and assign the first element of the given array. After that, we start a for loop that traverses the whole array starting from the second element. Within the loop, we check whether the current element of the given array is present in the temporary array or not. If the element already exists, then we skip it. Otherwise, we insert that element in the temporary array. Hence, our temporary array consists of all the distinct elements of the given array after removing duplicates.
public class Exercise7
{
public static void main(String[] args) {
int[] myarray={3, 5, 1, 3, 3, 2, 5, 3, 1, 1, 1, 4, 2, 3, 3, 1, 10, 4, 8, 1, 3, 8};
int[] temp_array=new int[myarray.length];
System.out.println("Array Elements...");
for(int i=0;i<myarray.length-1;i++)
{
System.out.print(myarray[i]+"\t");
}
temp_array[0]=myarray[0];
int cnt=1;
for(int i=1;i<myarray.length;i++)
{ boolean exists=false;
int x=myarray[i];
for(int j=0;j<temp_array.length;j++)
{
if(x==temp_array[j])
{
exists=true;
break;
}
}
if(!exists)
{
temp_array[cnt]=x;
cnt++;
}
exists=false;
}
System.out.println("\nArray Elements After Removing Duplicates...");
for(int i=0;i<cnt;i++)
{
System.out.print(temp_array[i]+"\t");
}
}
}
Output