Find Most Frequent Element
This program finds the most frequent element in an array.
Problem Statement
Write a Java program to find the most frequent element in an integer array.
Source Code
| 1 | import java.util.HashMap; |
| 2 | public class MostFrequentElement { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Most Frequent Element"); |
| 5 | int[] arr = {1,2,2,3,3,3,4,4,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 | int maxFreq=0, element=-1; |
| 11 | for(int key:freq.keySet()){ |
| 12 | if(freq.get(key)>maxFreq){ |
| 13 | maxFreq=freq.get(key); |
| 14 | element=key; |
| 15 | } |
| 16 | } |
| 17 | System.out.println("Most frequent element: "+element+" occurs "+maxFreq+" times"); |
| 18 | } |
| 19 | } |
Program Output
Eduinq Most Frequent Element Most frequent element: 4 occurs 4 times
Explanation
A HashMap stores the frequency of each element, and a loop scans the map's keys to find the element with the highest frequency, demonstrating how to find the most frequent element in an array.