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
Array arr initialized with integers. - HashMap stores element as key and frequency as value. - Loop iterates through array, updating frequency. - Second loop prints frequencies. - Together demonstrates frequency analysis. Conclusion: Shows how arrays can be analyzed for element frequency.