Java ProgramsArraysFind Most Frequent Element

Find Most Frequent Element in Java

intermediate·  Arrays  ·  Array

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.

Input
[4, 2, 4, 7, 2, 4]
Output
Most frequent element: 4 (3 times)

Java Program

Java
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

Most frequent element: 4 (3 times)

Core Logic

Building the frequency map first, then scanning it once for the highest count, finds the winner in two simple passes.

How It Works
  1. 1A LinkedHashMap<Integer, Integer> named freq tracks each element's count, exactly like counting element frequency.
  2. 2freq.getOrDefault(num, 0) reads the current count, or 0 if unseen, then freq.put(num, ...) stores the incremented count.
  3. 3maxElement and maxCount track the best candidate seen so far while walking entrySet().
  4. 4Whenever an entry's count exceeds maxCount, both maxElement and maxCount are updated to that entry.
In [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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

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

LinkedHashMapgetOrDefault()running maximum

Approach 2: Java 8

Java
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

Most frequent element: 4 (3 times)

Core Logic

Once the frequency map exists, a stream can find its highest-valued entry directly instead of a manual running-maximum loop.

How It Works
  1. 1Arrays.stream(arr).boxed() turns the int[] into a Stream<Integer>.
  2. 2Collectors.groupingBy(num -> num, Collectors.counting()) groups equal elements together and counts how many are in each group.
  3. 3freq.entrySet().stream().max(Map.Entry.comparingByValue()) compares every entry by its count and keeps the single largest one, wrapped in an Optional.
  4. 4.orElseThrow() unwraps the result, since the array is known not to be empty here.
Grouping [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.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: groupingBy() still visits every element once to build the map, and max() then makes one pass over its entries to find the largest.

Key Concepts

StreamCollectors.groupingBy()Map.Entry.comparingByValue()

Related Programs