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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read