Removing duplicates from an array.
Hint: Convert Array to Set
Here’s a Java program that removes duplicates from an array:
import java.util.Arrays; import java.util.HashSet; public class RemoveDuplicatesFromArray { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 2, 3, 5, 6, 1, 7}; // Convert array to HashSet to remove duplicates HashSet<Integer> uniqueElements = new HashSet<>(); for (int element : array) { uniqueElements.add(element); } // Convert the unique elements back to an array int[] newArray = new int[uniqueElements.size()]; int index = 0; for (int element : uniqueElements) { newArray[index++] = element; } System.out.println("Original array: " + Arrays.toString(array)); System.out.println("Array without duplicates: " + Arrays.toString(newArray)); } }
This program first creates a `HashSet` called `uniqueElements` to store the unique elements from the array. It iterates over each element in the array and adds it to the set. Since `HashSet` does not allow duplicates, only unique elements will be stored.
Then, the program creates a new array called `newArray` with the size of the `uniqueElements` set. It iterates over the set and assigns each element to the corresponding index in the new array.
Finally, it prints both the original array and the array without duplicates using `Arrays.toString()` method to convert the arrays to strings.
When you run the program, the output will be:
Original array: [1, 2, 3, 4, 2, 3, 5, 6, 1, 7]
Array without duplicates: [1, 2, 3, 4, 5, 6, 7]
As you can see, the duplicates (2, 3, and 1) have been removed from the array.