mostOccurrences method
Returns an Occurrence of the most common value and its frequency,
or null if the iterable is empty.
The iterable is read once, so a lazy source (map, where, a
generator) runs its callbacks once. Ties go to the value seen first.
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
Occurrence<int>? mostOccurrences() {
// The old code called isEmpty and then looped, running a lazy source
// twice. The shared counter reads it once, in first-seen order, so ties
// are deterministic instead of following HashMap order.
final MapEntry<int, int>? mostCommonEntry = pickFrequencyEntry(
frequencyMapOf<int>(this),
// Strict comparison: on a tie the first-seen value wins.
(int candidate, int best) => candidate > best,
);
// No entry means the iterable was empty.
if (mostCommonEntry == null) {
return null;
}
return Occurrence<int>(mostCommonEntry.key, mostCommonEntry.value);
}