Write a Java program to remove duplicates from an array.

import java.util.Arrays;
import java.util.LinkedHashSet;

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 2, 4, 3, 5, 6, 5, 7, 8, 9};
        System.out.println("Original Array: " + Arrays.toString(array));

        // Using LinkedHashSet to remove duplicates
        LinkedHashSet<Integer> set = new LinkedHashSet<>();
        for (int i : array) {
            set.add(i);
        }

        //Convert set back to array
        int[] uniqueArray = set.stream().mapToInt(Integer::intValue).toArray();
        System.out.println("Array without duplicates: " + Arrays.toString(uniqueArray));
    }
}
Original Array: [1, 2, 3, 2, 4, 3, 5, 6, 5, 7, 8, 9]
Array without duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The program first prints the original array, then it uses a LinkedHashSet to remove the duplicates. A LinkedHashSet is a collection that does not allow duplicate elements and keeps the insertion order.

It then converts the set back to an array using the stream() method and the mapToInt() method. The stream() method returns a sequential Stream of the elements in the set, the mapToInt() method returns an IntStream which is a stream of primitive int-valued elements. Finally, the toArray() method is used to convert the IntStream back to an array.

Leave a Reply

Your email address will not be published. Required fields are marked *