Java Program to Remove Duplicate Elements in an Array

In this post, we will write a Java program to remove duplicate integer elements in an Array.
There are many ways we can write logic to remove duplicate integer elements in an Array.

Using temp Array

To remove the duplicate element from an array, the array must be in sorted order. If an array is not sorted, you can sort it by calling Arrays.sort(arr) method.
import java.util.Arrays;

public class DuplicateFromArray {

    public static void main(final String[] args) {

        final int[] a = { 10, 20, 30, 40, 50, 50, 10, 20 };
        Arrays.sort(a);// sorting array
       removeDuplicate(a);
    }

    private static void removeDuplicate(final int[] a) {

        final int[] temp = new int[a.length];

        int j = 0;
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] != a[i + 1]) {
                temp[j++] = a[i];
            }
        }
        temp[j++] = a[a.length - 1];

        for (int i = 0; i < j; i++) {
             a[i] = temp[i];
        }

        for (int i = 0; i < j; i++) {
             System.out.println(temp[i]);
        }
    }
}
Output:
10
20
30
40
50

Using HashSet

Let's use HashSet provided add() method to remove duplicates from an array. The add() method returns true if this set did not already contain the specified element.
import java.util.HashSet;
import java.util.Set;

public class DuplicateFromArray {

   public static void main(final String[] args) {
       final Integer[] a = {10,20,30,40,50,50,10,20};
       removeDuplicates(a);
   }
 
  private static void removeDuplicates(final Integer[] a){
      final Set<Integer> set = new HashSet<Integer>();
   
      final Integer[] temp = new Integer[a.length];
      int j = 0;
      for (final Integer element : a) {
          if(set.add(element)){
             temp[j++] = element;
          }
      }
  
      // display temp array
      for (int i = 0; i < j; i++) {
          System.out.println(temp[i]);
      }
   }
}
Output:
10
20
30
40
50


Comments