Frequency Distribution of Array
This program prints frequency distribution of elements in an array.
Problem Statement
Write a Java program to print frequency distribution of elements in an integer array.
Source Code
| 1 | import java.util.HashMap; |
| 2 | public class FrequencyDistribution { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Frequency Distribution"); |
| 5 | int[] arr = {1,2,2,3,3,3,4,4}; |
| 6 | HashMap<Integer,Integer> freq = new HashMap<>(); |
| 7 | for(int num:arr){ |
| 8 | freq.put(num,freq.getOrDefault(num,0)+1); |
| 9 | } |
| 10 | System.out.println("Element | Frequency"); |
| 11 | for(int key:freq.keySet()){ |
| 12 | System.out.println(" "+key+" | "+freq.get(key)); |
| 13 | } |
| 14 | } |
| 15 | } |
Program Output
Eduinq Frequency Distribution Element | Frequency 1 | 1 2 | 2 3 | 3 4 | 2
Explanation
A HashMap stores the frequency of each array element, and a loop prints this data in a simple tabular format under Element and Frequency columns, demonstrating a frequency distribution report.