sortByValue method

void sortByValue([
  1. Comparator<V>? comparator
])

Sorts a map of type Map<K, V> (in place) using the map values.

Note: If V does not extend Comparable a valid Comparator<V> is required.

Implementation

void sortByValue([Comparator<V>? comparator]) {
  final tmp = entries.toList();
  if (isEmpty) return;
  if (comparator != null) {
    tmp.sort((left, right) => comparator(left.value, right.value));
  } else if (values.first is Comparable) {
    tmp.sort(
      (left, right) => (left.value as Comparable).compareTo(right.value),
    );
  } else {
    throw ErrorOfType<SortingNotSupported<V>>(
        message: 'Error trying to sort a map of type Map<$K, $V>.',
        invalidState: 'Type \'$V\' is not comparable.',
        expectedState: 'Try calling sortByValue() specifying '
            'a valid comparator for type \'$V\'.');
  }
  clear();
  addEntries(tmp);
}