1. Introduction
In Java, one might encounter situations where it’s necessary to remove duplicate elements from an array. This process helps in keeping only the unique elements in the array. In this post, we will demonstrate how to achieve this by converting the array to a Set, as a Set in Java does not allow duplicate elements.
2. Program Steps
1. Define and initialize an array with some elements.
2. Convert the array to a HashSet to remove any duplicate elements.
3. Convert the HashSet back to an array.
4. Display the resultant array which contains only unique elements.
3. Code Program
import java.util.HashSet;
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
// Step 1: Define and initialize an array with some elements
Integer[] array = {1, 2, 3, 4, 5, 1, 3, 5};
// Step 2: Convert the array to a HashSet to remove any duplicate elements
HashSet<Integer> uniqueElements = new HashSet<>(Arrays.asList(array));
// Step 3: Convert the HashSet back to an array
Integer[] uniqueArray = uniqueElements.toArray(new Integer[0]);
// Step 4: Display the resultant array
System.out.println("Array after removing duplicates: " + Arrays.toString(uniqueArray));
}
}
Output:
Array after removing duplicates: [1, 2, 3, 4, 5]
4. Step By Step Explanation
In Step 1, we define and initialize an Integer array array containing some elements, including duplicates.
In Step 2, we convert the array to a HashSet named uniqueElements using Arrays.asList(array). The HashSet automatically removes any duplicate values.
In Step 3, we convert the HashSet back to an array named uniqueArray by calling the toArray method on uniqueElements.
Finally, in Step 4, we print out the uniqueArray using Arrays.toString() method which now contains only the unique elements from the original array.