Find Most Frequent Element in Java
Problem
The most frequent element is whichever value has the highest count once every element's occurrences have been tallied.
Given an array of integers, find the element that appears the most times, along with its count.
Java Program
import java.util.LinkedHashMap;
import java.util.Map;
public class MostFrequentElement {
public static void main(String[] args) {
int[] arr = {4, 2, 4, 7, 2, 4};
Map<Integer, Integer> freq = new LinkedHashMap<>();
for (int num : arr) {
// getOrDefault(num, 0) reads the current count, or 0 if unseen, then increments it
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
int maxElement = arr[0];
int maxCount = 0;
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
if (entry.getValue() > maxCount) { // new highest count found
maxElement = entry.getKey();
maxCount = entry.getValue();
}
}
System.out.println("Most frequent element: " + maxElement + " (" + maxCount + " times)");
}
}Output
Core Logic
Building the frequency map first, then scanning it once for the highest count, finds the winner in two simple passes.
- 1A
LinkedHashMap<Integer, Integer>namedfreqtracks each element's count, exactly like counting element frequency. - 2
freq.getOrDefault(num, 0)reads the current count, or0if unseen, thenfreq.put(num, ...)stores the incremented count. - 3
maxElementandmaxCounttrack the best candidate seen so far while walkingentrySet(). - 4Whenever an entry's count exceeds
maxCount, bothmaxElementandmaxCountare updated to that entry.
[4, 2, 4, 7, 2, 4], 4 ends with a count of 3 — higher than 2 or 7 — so it's reported as the most frequent element.Key Point: Using > rather than >= when updating the maximum means the first element to reach the highest count wins any tie, keeping the result deterministic.
Why: Building the frequency map visits every element once and holds one entry per distinct value, up to n in the worst case.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class MostFrequentElementStream {
public static void main(String[] args) {
int[] arr = {4, 2, 4, 7, 2, 4};
Map<Integer, Long> freq = Arrays.stream(arr).boxed()
.collect(Collectors.groupingBy(num -> num, Collectors.counting()));
// Compares every entry by its count and keeps the largest one
Map.Entry<Integer, Long> maxEntry = freq.entrySet().stream()
.max(Map.Entry.comparingByValue())
.orElseThrow();
System.out.println("Most frequent element: " + maxEntry.getKey() + " (" + maxEntry.getValue() + " times)");
}
}
Output
Core Logic
Once the frequency map exists, a stream can find its highest-valued entry directly instead of a manual running-maximum loop.
- 1
Arrays.stream(arr).boxed()turns theint[]into aStream<Integer>. - 2
Collectors.groupingBy(num -> num, Collectors.counting())groups equal elements together and counts how many are in each group. - 3
freq.entrySet().stream().max(Map.Entry.comparingByValue())compares every entry by its count and keeps the single largest one, wrapped in anOptional. - 4
.orElseThrow()unwraps the result, since the array is known not to be empty here.
[4, 2, 4, 7, 2, 4] produces counts for each element, and max() picks out 4: 3 as the largest entry.Key Point: Map.Entry.comparingByValue() is a ready-made comparator that compares entries purely by their value — no need to write a custom Comparator for this common case.
Why: groupingBy() still visits every element once to build the map, and max() then makes one pass over its entries to find the largest.