Java Online Compiler
Example: Array Element Frequency Counter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Array Element Frequency Counter import java.util.HashMap; import java.util.Map; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] numbers = {10, 20, 20, 10, 30, 10, 40, 20}; // Step 2: Create a HashMap to store element frequencies // Key: Array element, Value: Frequency count Map<Integer, Integer> frequencyMap = new HashMap<>(); // Step 3: Iterate through the array to count frequencies for (int number : numbers) { // Check if the element is already in the map if (frequencyMap.containsKey(number)) { // If yes, increment its count frequencyMap.put(number, frequencyMap.get(number) + 1); } else { // If no, add it to the map with a count of 1 frequencyMap.put(number, 1); } } // Step 4: Print the resulting frequency map System.out.println("Element Frequencies:"); for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue() + " times"); } } }
Output
Clear
ADVERTISEMENTS