sortByKey method

void sortByKey([
  1. Comparator<K>? comparator
])

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

Note: If K does not extend Comparable a valid Comparator<K> must be provided.

Implementation

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