How to remove duplicate elements of an array in java?

Java 8Object Oriented ProgrammingProgramming

To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements in case of a match you got your duplicate element.

One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of the outer loop) to avoid repetitions.

Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add a library to your project.

<dependencies>
   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
   </dependency>
</dependencies>

This package provides a class named ArrayUtils using the remove() method of this class you can delete the detected duplicate elements of the given array.

Example

import java.util.Arrays;
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;
public class DeleteDuplicate {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      for(int i=0; i<myArray.length-1; i++) {
         for (int j=i+1; j<myArray.length; j++) {
            if(myArray[i] == myArray[j]) {
               myArray = ArrayUtils.remove(myArray, j);
            }
         }
      }
      System.out.println("Array after removing elements ::"+Arrays.toString(myArray));
   }
}

Output

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
232
232
65
47
89
42
The array created is :: [232, 232, 65, 47, 89, 42]
Array after removing elements :: [232, 65, 47, 89, 42]
raja
Published on 09-Jan-2018 10:06:12
Advertisements