The 30 second answer
I count with groupingBy and counting, then stream the entries and take max with Map.Entry.comparingByValue. That returns an Optional of an entry, so I map it to the key and it stays empty for an empty list. Before coding I ask what to do on a tie: return any, the first one seen, or all of them.
var items = List.of("b", "a", "c", "a", "b", "a");
var counts = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
var mostFrequent = counts.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey);
// Optional[a]Ties: the default groupingBy map has no defined order, so which tied element max returns is not something to rely on. Two common fixes:
// Every element that shares the top count:
long maxCount = counts.values().stream().mapToLong(Long::longValue).max().orElse(0);
var allModes = counts.entrySet().stream()
.filter(e -> e.getValue() == maxCount)
.map(Map.Entry::getKey)
.toList();
// The tied element that appeared first in the input:
var firstSeenMode = items.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.reduce((best, e) -> e.getValue() > best.getValue() ? e : best)
.map(Map.Entry::getKey);The reduce only replaces the current best on a strictly greater count, so the first-seen element wins a tie.
Complexity: O(n) expected time to count and O(k) to scan the k distinct elements, with O(k) space for the map. Sorting the entries just to read the first one would cost O(k log k) for no reason.
Edge cases: an empty list gives Optional.empty(), so do not call get() blindly. groupingBy throws NullPointerException for a null element, so filter nulls first if they are allowed. Elements of a custom class need correct equals and hashCode.
What interviewers listen for: that you return Optional rather than null, ask about ties before coding, and use max instead of a full sort.
Sources (4)
- Collectors.groupingBy and countingdocs.oracle.com
- Map.Entry.comparingByValuedocs.oracle.com
- Stream.max and reducedocs.oracle.com
- Optionaldocs.oracle.com