Remove Duplicates from Array in Java
Remove duplicate elements from an array (sorted or unsorted).
Last updated: 11 January 2026
Method 1: Using HashSet
Easiest way using collection.
Main.javaRun in Compiler →
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {10, 20, 20, 30, 30, 40, 50, 50};
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
System.out.println("Unique elements: " + set);
}
}Output:
Unique elements: [50, 20, 40, 10, 30]
Explanation
HashSet only stores unique elements automatically.
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler