Remove Duplicates from Array in Java
In this lesson: Remove duplicate elements from an array in Java using loops, sorting and Set — code with output. In Hindi & English.
The problem
An array can contain repeated values, like {1, 2, 2, 3, 4, 4, 5}. Removing duplicates means keeping only one copy of each — {1, 2, 3, 4, 5}. The cleanest way in Java uses a HashSet, which only holds unique values.
Using a HashSet
import java.util.*;
int[] arr = {1, 2, 2, 3, 4, 4, 5};
Set<Integer> unique = new HashSet<>();
for (int x : arr) {
unique.add(x); // duplicates ignored
}
System.out.println(unique);
Adding every element to a HashSet keeps only the distinct ones — duplicates are simply ignored. This is the shortest and fastest common approach.
Dry run
| x | Already in the Set? | Set now |
|---|---|---|
| 1 | no | {1} |
| 2 | no | {1,2} |
| 2 | yes | {1,2} (skip) |
| 3 | no | {1,2,3} |
| 4 | no | {1,2,3,4} |
| 4 | yes | {1,2,3,4} (skip) |
| 5 | no | {1,2,3,4,5} |
Each element is added to the Set. If it is already there (the repeated 2 and 4), the Set ignores it. Only unique values remain.
A manual approach
int[] arr = {1, 2, 2, 3};
ArrayList<Integer> result = new ArrayList<>();
for (int x : arr) {
if (!result.contains(x)) { // not seen yet
result.add(x);
}
}
System.out.println(result);
Without a Set, you loop and add each element only if it is not already in the results. This works but is slower (O(n²)) because contains checks every kept item each time.
Keeping the order
A plain HashSet does not keep the original order. If order matters, use a LinkedHashSet:
Set<Integer> unique = new LinkedHashSet<>(); // keeps items in the order they were first added
LinkedHashSet removes duplicates and preserves the insertion order — the best of both.
Common mistakes
- Expecting HashSet to keep order. Use LinkedHashSet if order matters.
- Using the manual method for large arrays. It is O(n²) — prefer a Set.
- Forgetting the import. Sets come from
java.util. - Using primitives in a Set. Use
Integer, notint.
Summary
- Removing duplicates keeps one copy of each value.
- A HashSet drops duplicates automatically — the easiest way.
- A manual loop with
containsalso works but is slower. - Use LinkedHashSet to keep the original order.
- The HashSet method is about O(n); the manual one is O(n²).
Next, learn sets in HashSet vs TreeSet, or work with arrays in Java arrays.
