leastOccurrences method

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

Finds the least common value in the list.

Returns an Occurrence containing the least common value and its frequency. If the list is empty, returns null. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
Occurrence<double>? leastOccurrences() {
  if (isEmpty) {
    return null;
  }

  // Create a new HashMap to store each double and its frequency.
  final HashMap<double, int> frequencyMap = HashMap<double, int>();

  // Iterate over each double in the list.
  for (final double item in this) {
    // Update the frequency of the current double in the map,
    // or set it to 1 if it's not in the map yet.
    // ignore: saropa_lints/require_future_error_handling -- Map.update is synchronous; there is no future to handle
    frequencyMap.update(item, (int value) => value + 1, ifAbsent: () => 1);
  }

  // Find and return the key with the LOWEST value (frequency) in the map.
  final MapEntry<double, int>? leastCommonEntry = frequencyMap.entries.fold(
    null,
    (MapEntry<double, int>? previous, MapEntry<double, int> element) =>
        previous == null || element.value < previous.value ? element : previous,
  );

  if (leastCommonEntry == null) {
    return null;
  }

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