4.Program to print the duplicate elements of an array
💡Code:
import java.util.HashMap; import java.util.Map; public class DuplicateElements7078 { public static void main(String[] args) { // Example array int[] array = {1, 2, 3, 4, 2, 1, 3, 5, 6, 7, 7, 8, 9, 9, 5}; // Display the original array System.out.println("Original Array:"); displayArray(array); // Find and print duplicate elements System.out.println("\nDuplicate Elements:"); printDuplicateElements(array); } // Method to find and print duplicate elements private static void printDuplicateElements(int[] arr) { MapfrequencyMap = new HashMap<>(); // Count the frequency of each element for (int element : arr) { frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1); } // Print elements with frequency greater than 1 for (Map.Entry entry : frequencyMap.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey()); } } } // 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 :
.png)