Array Java Programs

Remove duplicate elements in an array

In this tutorial you will learn how to write a program to remove duplicates from an array.

Below are the approaches we will follow to write our program:

In this program we will first create an array and add some elements in it.And then we will print the occurrence of each element of an array.And only print the elements that occurred only once.And will not print the elements that occurred more than once.

How will our program behave?

Our program will take an array as input and then count the occurrences of each element. After counting, only the elements that occur only once will be printed as output.

Remove duplicate elements from array in Java

import java.util.*;

public class ArrayExample {	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the size of array: ");
		int n = sc.nextInt();
		int arr[] = new int[n];
		int ar[] = new int[100];
		Arrays.fill(ar, 0);
		System.out.println("Enter " + n + " array elements between 0 to 100 ");
		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		System.out.println("Array elements after removing duplicates");
		for (int i = 0; i < n; i++) {
			ar[arr[i]]++;
			if (ar[arr[i]] == 1) {
				System.out.println(arr[i]);
			}
		}
	}
}

Output

Enter the size of array: 
5
Enter 5 array elements between 0 to 100 
23
45
23
56
34
Array elements after removing duplicates
23
45
56
34

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs