leastOccurrences method

  1. @useResult
Occurrence<int>? leastOccurrences()

Returns an Occurrence of the least 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>? leastOccurrences() {
  // Single pass for the same reason as mostOccurrences (isEmpty plus a loop
  // ran a lazy source twice); first-seen order makes ties deterministic.
  final MapEntry<int, int>? leastCommonEntry = 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 (leastCommonEntry == null) {
    return null;
  }

  return Occurrence<int>(leastCommonEntry.key, leastCommonEntry.value);
}