Java Online Compiler
Example: Array Element Frequency using HashMap in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Array Element Frequency using HashMap import java.util.HashMap; import java.util.Map; import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Initialize the array int[] arr = {10, 20, 20, 10, 10, 30, 40, 50, 20, 40}; // Step 2: Create a HashMap to store element frequencies // The key will be the array element, and the value will be its count. Map<Integer, Integer> frequencyMap = new HashMap<>(); // Step 3: Iterate through the array and update frequencies in the map for (int element : arr) { // Using getOrDefault to simplify logic: // If element exists as a key, get its current count and increment. // If element does not exist, default count to 0 and then increment to 1. frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1); } // Step 4: Print the frequencies from the HashMap System.out.println("Element Frequencies:"); for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue() + " times"); } } }
Output
Clear
ADVERTISEMENTS