Java Program to Remove Duplicate Elements From the Array
Last Updated :
16 Nov, 2024
Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set
, which automatically eliminates duplicates. This method can be used even if the array is not sorted.
Example:
Java
// Java Program to Remove Duplicate
// Elements From the Array using Set
import java.util.*;
class GFG {
// Function to remove duplicate from array
public static void remove(int[] a)
{
LinkedHashSet<Integer> s
= new LinkedHashSet<Integer>();
// adding elements to LinkedHashSet
for (int i = 0; i < a.length; i++)
s.add(a[i]);
System.out.print(s);
}
public static void main(String[] args)
{
int a[] = {1, 2, 2, 3, 3, 4, 5};
// Function call
remove(a);
}
}
Sets like LinkedHashSet maintains the order of insertion, so it will remove duplicates and elements will be printed in the same order in which it is inserted.
There are many other ways to remove duplicate elements from an array. The approach and illustrations of those methods are mentioned below:
In this approach, it removes duplicates from an array by sorting it first and then copying the unique elements to a temporary array by copying them back to the original array.
Approach:
- Create a temporary array temp[] to store unique elements.
- Sort the input array first then traverse input array and copy all the unique elements of a[] to temp[]. Also, keep count of unique elements. Let this count be j.
- Copy j elements from temp[] to a[].
Implementation:
Java
// Java Program to Remove Duplicate Elements
// From the Array using extra space
import java.util.Arrays;
public class Main {
public static int remove(int a[], int n)
{
if (n == 0 || n == 1) {
return n;
}
// Sort the input array
Arrays.sort(a);
// create another array for only storing
// the unique elements
int[] t = new int[n];
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] != a[i + 1]) {
t[j++] = a[i];
}
}
// Adding last element to the array
t[j++] = a[n-1];
// Changing the original array
for (int i = 0; i < j; i++) {
a[i] = t[i];
}
return j;
}
public static void main(String[] args)
{
int a[] = { 1, 2, 3, 1, 4, 2, 1, 5 };
int n = a.length;
n = remove(a, n);
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
This approach removes duplicates from an array by sorting it first and then using a single pointer to track the unique elements. It ensures that only the unique elements are retained in the original array.
Approach:
- Sort the input array first to group duplicates together.
- Initialize a variable
j
to track the last unique element's position. - Traverse the array from index 1 by comparing each element with the last unique element (at index
j
). - If they are different, increment
j
and place the new unique element at index j
. - At last, return
j + 1
, which is the count of unique elements, and they will be in sorted order due to the initial sorting.
Implementation:
Java
// Java Program to Remove Duplicate Elements
// From the Array using extra space
import java.util.Arrays;
public class Main {
// Function to remove duplicates from the array
public static int remove(int[] a) {
if (a.length == 0) {
return 0;
}
// Sort the array to bring duplicates together
Arrays.sort(a);
// j is the index of the last unique element found
int j = 0;
for (int i = 1; i < a.length; i++) {
// If current element is different from the last unique element
if (a[i] != a[j]) {
j++;
a[j] = a[i]; // Move the unique element to the next position
}
}
return j + 1; // Return the count of unique elements
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 1, 4, 2, 1, 5};
int n = remove(a);
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
3. Using Frequency array
We can use the frequency array, if the range of the number in the array is limited, or we can also use a set or map interface to remove duplicates, if the range of numbers in the array is too large.
Approach:
- Find the Maximum element (m) in the array.
- Create a new array of size m+1.
- Now, traverse the input array and count the frequency of every element in the input array.
- Now, traverse the frequency array and check for the frequency of every number if the frequency of the particular element is greater than 0 then print the number.
Implementation:
Java
// Java Program to Remove Duplicate Elements
// From the Array by maintaining frequency array
import java.util.*;
class GFG {
public static void main(String[] args)
{
int a[] = { 1, 2, 3, 1, 4, 2, 1, 5 };
int n = a.length;
// m will have the maximum element in the array
int m = 0;
for (int i = 0; i < n; i++) {
m = Math.max(m, a[i]);
}
// create the frequency array
int[] f = new int[m + 1];
// increament the value at a[i]th index
// in the frequency array
for (int i = 0; i < n; i++)
{
f[a[i]]++;
}
for (int i = 0; i < m + 1; i++)
{
// if the frequency of the particular element
// is greater than 0, then print it once
if (f[i] > 0) {
System.out.print(i + " ");
}
}
}
}
4. Using HashMap
The above frequency method will not be useful if the number is greater than 106 or if the array is of strings. In this case, we have to use HashMap.
Approach:
- Create a HashMap to store the unique elements.
- Traverse the array.
- Check if the element is present in the HashMap.
- If yes, continue traversing the array.
- Else, print the element and store the element in HashMap.
Implementation:
Java
// Java Program to Remove Duplicate Elements
// From the Array using HashMap
import java.util.HashMap;
class GFG {
static void remove(int[] a, int n)
{
HashMap<Integer, Boolean> hm = new HashMap<>();
for (int i = 0; i < n; ++i) {
// print element if it is not
// in the hash map and Insert
// the element in the hash map
if (hm.get(a[i]) == null)
{
System.out.print(a[i] + " ");
hm.put(a[i], true);
}
}
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 1, 4, 2, 1, 5 };
int n = arr.length;
remove(arr, n);
}
}
Similar Reads
Java Program to Remove Duplicate Entries from an Array using TreeSet Features of TreeSet is the primary concern it is widely used in remove duplicates in the data structure as follows: TreeSet implements the SortedSet interface. So, duplicate values are not allowed and will be leftovers.Objects in a TreeSet are stored in a sorted and ascending order.TreeSet does not
3 min read
Java Program To Remove All The Duplicate Entries From The Collection As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.The HashSet class implements the Set interface,
3 min read
Java Program to Remove a Specific Element From a Collection remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index fr
3 min read
Java Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
How to Remove Duplicate Elements from the Vector in Java? Using LinkedHashSet and TreeSet, duplicate elements are removed. Because the LinkedHashSet and TreeSet do not accept duplicate elements. Example: Input : vector = [1, 2, 3, 4, 2, 4] Output: vector = [1, 2, 3, 4] Input : vector = [a, b, a, c, d, a] Output: vector = [a, b, c, d]Approach 1: Using Linke
3 min read
How to Remove Duplicate Elements From Java LinkedList? Linked List is a part of the Collection in java.util package. LinkedList class is an implementation of the LinkedList data structure it is a linear data structure. In LinkedList due to the dynamical allocation of memory, insertions and deletions are easy processes. For removing duplicates from Examp
4 min read
Java Program to Remove an Element from ArrayList using ListIterator ListIterator.remove() method removes the last element from the list that was returned by next() or previous() cursor positions. It can be called only once per call to next or previous. It can be made only if the operation â add(E) has not called after the last call to next or previous. Internal work
4 min read
How to Prevent the Addition of Duplicate Elements to the Java ArrayList? Ever wondered how you can make an ArrayList unique? Well, in this article we'll be seeing how to prevent the addition of duplicates into our ArrayList. If an ArrayList have three duplicate elements, but at the end, only the ones which are unique are taken into the ArrayList and the repetitions are n
3 min read
Remove first element from ArrayList in Java Given an ArrayList collection in Java, the task is to remove the first element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 40, 50] Output: [20, 30, 40, 50]Input: ArrayList[] = [1, 1, 2, 2, 3]Output: [1, 2, 2, 3]We can use the remove() method of ArrayList container in Java to remov
2 min read
Removing last element from ArrayList in Java Given an ArrayList collection in Java, the task is to remove the last element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 1, 2] Output: [10, 20, 30, 1] After removing the last element 2, the ArrayList is: [10, 20, 30, 1] Input: ArrayList[] = [1, 1, 2, 2, 3] Output: [1, 1, 2, 2] Af
2 min read