JAVA SP T


Lets dive into snapshot of my programs!💻

21.Program to Remove Duplicate Element in an array

💡Code:

  
                import java.util.Arrays;

                public class RemoveDuplicates7078 {
                    public static void main(String[] args) {
                        // Example array with duplicates
                        int[] array = {5, 2, 8, 1, 9, 3, 6, 2, 5, 9};
                
                        // Display the original array
                        System.out.println("Original Array:");
                        displayArray(array);
                
                        // Remove duplicates
                        int[] uniqueArray = removeDuplicates(array);
                
                        // Display the array after removing duplicates
                        System.out.println("\nArray after removing duplicates:");
                        displayArray(uniqueArray);
                    }
                
                    // Method to remove duplicates from an array
                    private static int[] removeDuplicates(int[] arr) {
                        int length = arr.length;
                
                        // Check for empty or null array
                        if (length == 0 || arr == null) {
                            return arr;
                        }
                
                        // Sort the array to group duplicates together
                        Arrays.sort(arr);
                
                        // Count the number of unique elements
                        int uniqueCount = 1;
                        for (int i = 1; i < length; i++) {
                            if (arr[i] != arr[i - 1]) {
                                uniqueCount++;
                            }
                        }
                
                        // Create a new array with unique elements
                        int[] uniqueArray = new int[uniqueCount];
                        uniqueArray[0] = arr[0];
                        int j = 1;
                        for (int i = 1; i < length; i++) {
                            if (arr[i] != arr[i - 1]) {
                                uniqueArray[j++] = arr[i];
                            }
                        }
                
                        return uniqueArray;
                    }
                
                    // Method to display the elements of an array
                    private static void displayArray(int[] arr) {
                        for (int value : arr) {
                            System.out.print(value + " ");
                        }
                        System.out.println();
                    }
                }
                

               

📸Output :

output