Java Online Compiler
Example: Remove Duplicates Using HashSet in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Remove Duplicates Using HashSet import java.util.HashSet; import java.util.Arrays; public class Main { public static void main(String[] args) { int[] originalArray = {5, 2, 8, 2, 5, 1, 9, 8}; System.out.println("Original Array: " + Arrays.toString(originalArray)); // Step 1: Create a HashSet to store unique elements HashSet<Integer> uniqueElements = new HashSet<>(); // Step 2: Iterate through the original array and add elements to the HashSet // HashSet automatically handles uniqueness for (int element : originalArray) { uniqueElements.add(element); } // Step 3: Convert the HashSet back to an array (optional, can also use uniqueElements directly) // Note: The order of elements in the resulting array is not guaranteed to be the original order. int[] arrayWithoutDuplicates = new int[uniqueElements.size()]; int i = 0; for (int element : uniqueElements) { arrayWithoutDuplicates[i++] = element; } System.out.println("Array after removing duplicates (HashSet): " + Arrays.toString(arrayWithoutDuplicates)); } }
Output
Clear
ADVERTISEMENTS