Java program to remove duplicate element in array

Let’s learn to remove duplicate from array in java.

Remove duplicate from array java

To remove duplicate element from an array first the array must be in sorted order or sorted array. Here in this post we are going to learn to remove duplicate element in array using temporary array.

remove duplicate element in array

Now let’s see java program to remove duplicate elements,

public class RemoveDuplicatesDemo 
{
   public static int duplicateElement(int[] arrNumbers, int num)
   {  
      if(num == 0 || num == 1)
      {  
         return num;  
      }  
      int[] temp = new int[num];  
      int b = 0;  
      for(int a = 0; a < num - 1; a++)
      {  
         if(arrNumbers[a] != arrNumbers[a + 1])
         {  
            temp[b++] = arrNumbers[a];  
         }  
      }  
      temp[b++] = arrNumbers[num - 1]; 
      for(int a = 0; a < b; b++)
      {  
         arrNumbers[a] = temp[a];  
      }  
      return b;  
   }

   public static void main(String[] args) 
   {
      int[] arrInput = {2, 2, 6, 8, 8, 10, 12, 12};  
      int length = arrInput.length;  
      length = duplicateElement(arrInput, length);  
      // printing elements  
      for(int a = 0; a < length; a++)
      {
         System.out.print(arrInput[a] + " ");
      }
   }
}



Output:

2, 6, 8, 10, 12

In the above program we saw that to remove duplicate elements the condition was array should be in sorted order.

Also read – delete specified integer from an array in java

Meanwhile we can also remove duplicate elements in unsorted array. To do that first we need to sort given array. To sort array we are going to use Arrays.sort() method.

Now let’s see program,

import java.util.Arrays;

public class RemoveDuplicateExample 
{
   public static int removeDuplicate(int[] arrNumbers, int num)
   {  
      if(num == 0 || num == 1)
      {  
         return num;  
      }  
      int[] temp = new int[num];  
      int b = 0;  
      for(int a = 0; a < num - 1; a++)
      {  
         if(arrNumbers[a] != arrNumbers[a + 1])
         {  
            temp[b++] = arrNumbers[a];  
         }  
      }  
      temp[b++] = arrNumbers[num - 1];
      for(int a = 0; a < b; a++)
      {  
         arrNumbers[a] = temp[a];  
      }  
      return b;  
   } 

   public static void main(String[] args) 
   {
      int[] arrInput = {2, 12, 10, 6, 8, 8, 2, 14, 12 ,4};
      // first sort array
      Arrays.sort(arrInput);  
      int length = arrInput.length;  
      length = removeDuplicate(arrInput, length);
      for(int a = 0; a < length; a++)
      {
         System.out.print(arrInput[a] + " "); 
      }
   }
}



Output:

2 4 6 8 10 12 14