Google News
logo
Java Program to Remove Duplicate Elements in an Array
In the following example of Java program to remove duplicate elements in an array :
Program :
import java.util.Arrays;

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] arr = {13, 2, 3, 21, 4, 5, 18, 5, 6, 9, 13, 18};
        int[] newArr = removeDuplicates(arr);
        System.out.println(Arrays.toString(newArr));
    }

    public static int[] removeDuplicates(int[] arr) {
        int[] tempArr = new int[arr.length];
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDuplicate = false;
            for (int j = 0; j < index; j++) {
                if (arr[i] == tempArr[j]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                tempArr[index++] = arr[i];
            }
        }
        int[] newArr = new int[index];
        for (int i = 0; i < index; i++) {
            newArr[i] = tempArr[i];
        }
        return newArr;
    }
}
Output :
[13, 2, 3, 21, 4, 5, 18, 6, 9]
In this program, the removeDuplicates method takes an integer array as input and returns a new array with all the duplicate elements removed.

It first creates a new temporary array tempArr with the same size as the input array. It then iterates through the input array, and for each element, it checks if it is a duplicate by comparing it with the elements in the tempArr array.

If it is a duplicate, it skips it. If it is not a duplicate, it adds it to the tempArr array and increments the index variable.

Finally, it creates a new array newArr with the correct size (i.e., the number of unique elements), copies the elements from the tempArr array to the newArr array, and returns the newArr.