Introduction
Removing duplicate elements or characters is one of the most common programming problems in Java. It helps developers understand important concepts such as arrays, strings, loops, HashSet, LinkedHashSet, collections, and data structures.
Duplicate means the same value or character appears more than once in a collection or string.
For example:
Input:
Java Programming
After Removing Duplicates:
Jav Progmin
Another example with numbers:
Input Array:
10 20 30 20 40 10
Output
Java provides different approaches to remove duplicates:
- Using HashSet
- Using LinkedHashSet
- Using loops
- Using Java Streams
- Using arrays
Removing duplicates is frequently asked in Java interviews because it tests knowledge of collections and data handling.
In this tutorial, you will learn how to write Java programs to remove duplicate characters and duplicate elements, understand different approaches, analyze complexity, learn common mistakes, and prepare interview questions.
What is Removing Duplicates?
Removing duplicates means deleting repeated occurrences of elements while keeping only unique values.
Example:
Original String:
programming
Characters:
p r o g r a m m i n g
After Removing Duplicate Characters:
progamin
Here:
- r appears two times → keep one r
- g appears two times → keep one g
- m appears two times → keep one m
Final result contains only unique characters.
Why Remove Duplicates?
Duplicate removal is useful in many real-world applications:
- Removing repeated records from databases.
- Cleaning user data.
- Removing duplicate words from documents.
- Optimizing memory usage.
- Processing unique values in applications.
- Data analysis and reporting.
Syntax
Using HashSet:
HashSet set = new HashSet<>();
for(char ch : text.toCharArray()) {
set.add(ch);
}
HashSet automatically removes duplicate values because it stores only unique elements.
Java Remove Duplicate Characters Using HashSet
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
String text = "programming";
HashSet set = new HashSet<>();
String result = "";
for(char ch : text.toCharArray()) {
if(set.add(ch)) {
result = result + ch;
}
}
System.out.println("Original String: " + text);
System.out.println("After Removing Duplicates: " + result);
}
}
Output
After Removing Duplicates: progamin
Explanation of the Program
Step 1: Create String
String text = "programming";
This string contains duplicate characters.
Step 2: Create HashSet
HashSet set = new HashSet<>();
HashSet stores only unique characters.
Example:
Input:
p r o g r a m m i n g
HashSet:
p r o g a m i n
Step 3: Convert String into Characters
text.toCharArray()
This converts the string into a character array.
Step 4: Add Characters into Set
if(set.add(ch))
The add() method returns:
- true if the character is new.
- false if the character already exists.
Step 5: Create Result String
result = result + ch;
Only unique characters are added to the result.
Java Remove Duplicate Characters Using LinkedHashSet
HashSet does not maintain insertion order. If you want to preserve the original order, use LinkedHashSet.
import java.util.LinkedHashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
String text = "programming";
LinkedHashSet set = new LinkedHashSet<>();
for(char ch : text.toCharArray()) {
set.add(ch);
}
System.out.println("Unique Characters:");
for(char ch : set) {
System.out.print(ch);
}
}
}
Output
Java Remove Duplicate Characters Using StringBuilder
public class RemoveDuplicates {
public static void main(String[] args) {
String text = "success";
StringBuilder result = new StringBuilder();
for(int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if(result.indexOf(String.valueOf(ch)) == -1) {
result.append(ch);
}
}
System.out.println(result);
}
}
Output
Java Remove Duplicate Numbers from Array
import java.util.HashSet;
public class RemoveDuplicateNumbers {
public static void main(String[] args) {
int[] numbers = {10,20,30,20,40,10};
HashSet set = new HashSet<>();
for(int num : numbers) {
set.add(num);
}
System.out.println(set);
}
}
Output
Java Remove Duplicate Numbers While Maintaining Order
import java.util.LinkedHashSet;
public class RemoveDuplicateNumbers {
public static void main(String[] args) {
int[] numbers = {10,20,30,20,40,10};
LinkedHashSet set = new LinkedHashSet<>();
for(int num : numbers) {
set.add(num);
}
System.out.println(set);
}
}
Output
Algorithm
- Start the program.
- Read a string or array.
- Create a collection to store unique values.
- Traverse each element.
- Check whether the element already exists.
- If it does not exist, add it.
- Display unique elements.
- End the program.
Flowchart
Start
|
|
Read String/Array
|
|
Create Set
|
|
Read Each Element
|
|
Already Exists?
|
Yes No
| |
Ignore Add Element
|
Next Element
|
Display Result
|
End
Time Complexity
Using HashSet
Time complexity:
O(n)
Explanation:
Each element is checked once.
Using Nested Loop
Time complexity:
O(n²)
Because every element is compared with other elements.
Space Complexity
Using HashSet:
O(n)
Because extra memory is required to store unique elements.
Advantages of Removing Duplicates
- Improves data quality.
- Reduces unnecessary storage.
- Helps in data processing.
- Easy using Java Collections.
- Common real-world requirement.
Disadvantages
- Requires additional memory.
- Order may change when using HashSet.
- Large datasets require optimization.
Common Mistakes
1. Using HashSet When Order is Important
HashSet does not maintain insertion order.
Example:
HashSet<Character> set = new HashSet<>();
Use:
LinkedHashSet<Character> set = new LinkedHashSet<>();
2. Adding Duplicate Values Again
Incorrect:
result += ch;
without checking.
Correct:
if(set.add(ch))
3. Forgetting Case Sensitivity
Java treats A, a as different characters.
Convert to lowercase if required:
text.toLowerCase();
4. Not Handling Empty Input
Example:
Input:
""
Output
5. Using Incorrect Collection Type
For unique values:
Use:
Set
Not:
List
Real-Life Applications
Removing duplicates is used in:
Database Systems
Removing duplicate records from tables.
Search Engines
Removing repeated search results.
Data Cleaning
Cleaning large datasets before analysis.
User Management Systems
Avoiding duplicate user accounts.
E-Commerce Applications
Removing duplicate products from lists.
Summary
The Java Remove Duplicates Program is an important programming concept that helps developers understand how to handle repeated data and maintain unique values.
Java provides powerful collection classes like HashSet and LinkedHashSet to remove duplicates easily. HashSet provides better performance, while LinkedHashSet maintains the original insertion order.