2.Program to find the frequency of each element in the array
💡Code:
import java.util.HashMap;
import java.util.Map;
public class ElementFrequency7078 {
public static void main(String[] args) {
// Example array
int[] array = {1, 2, 3, 4, 2, 1, 3, 5, 1, 2, 4, 5};
// Create a map to store element frequencies
Map frequencyMap = new HashMap<>();
// Calculate frequency of each element
for (int element : array) {
frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1);
}
// Display the frequency of each element
System.out.println("Element frequencies:");
for (Map.Entry entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " times");
}
}
}
📸Output :