Frequency of Elements in Array
This program calculates frequency of each element in an array.
Problem Statement
Write a Java program to count frequency of each element in an integer array.
Source Code
| 1 | import java.util.HashMap; |
| 2 | public class ElementFrequency { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Element Frequency"); |
| 5 | int[] arr = {1,2,2,3,3,3,4}; |
| 6 | HashMap<Integer,Integer> freq = new HashMap<>(); |
| 7 | for(int num:arr){ |
| 8 | freq.put(num,freq.getOrDefault(num,0)+1); |
| 9 | } |
| 10 | for(int key:freq.keySet()){ |
| 11 | System.out.println("Element "+key+" occurs "+freq.get(key)+" times"); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Eduinq Element Frequency Element 1 occurs 1 times Element 2 occurs 2 times Element 3 occurs 3 times Element 4 occurs 1 times
Explanation
A HashMap stores each array element as a key and its frequency as the value, updated by a loop over the array, and a second loop prints these frequencies, demonstrating frequency analysis of array elements.