Java Program to remove duplicate elements in an Array (Best Program)

We can remove duplicate elements in an array in two ways: –

  • Using a temporary array
  • Using a separate index.

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

Remove Duplicate Elements in an Array using Temporary Array

Example 1

public class A {
public static void main(String[] args) {
 		int arr[] = {1,1,2,3,4,4,5};
		int len =arr.length;
		int temp[] =new int[arr.length];
		int j=0;
		for(int i=0; i<len-1;i++) {
			if(arr[i]!=arr[i+1]) {
				temp[j]=arr[i];
				j++;
			}
		}
		temp[j]=arr[arr.length-1];
		for(int m=0; m<=j; m++) {
			System.out.println(temp[m]);
		}
	}
Output:
1
2
3
4
5

You Also Learn –

Remove Duplicate Element in Array using a separate index

Example 1

public class A{
	public static void main(String[] args) {
 		int arr[] = {1,1,2,3,4,4,5};
		int len =arr.length;
		int j=0;
		for(int i=0; i<len-1;i++) {
			if(arr[i]!=arr[i+1]) {
				arr[j]=arr[i];
				j++;
			}
		}
		arr[j]=arr[arr.length-1];
		for(int m=0; m<=j; m++) {
			System.out.println(arr[m]);
		}
	}
Output:
1
2
3
4
5

Leave a Comment