sortWithKey<K extends Comparable<Object>> method

void sortWithKey<K extends Comparable<Object>>(
  1. K key(
    1. E
    )
)

Sorts this List according to the computed sort key.

The sort keys are cached, so this can be much more time-efficient (at the expense of space) than using sort with a custom comparison callback if comparisons are expensive.

K intentionally extends from Comparable<Object> and not from Comparable<K> so that this works with int and double types (which otherwise would not work because int and double implement Comparable<num>).

To use sortWithKey with keys that are easily comparable with a custom comparison function but that do not implement Comparable, use ComparableWrapper.

Implementation

void sortWithKey<K extends Comparable<Object>>(K Function(E) key) {
  final keyValues = [
    for (var element in this) MapEntry(key(element), element),
  ]..sort(_compareKeys);

  // Copy back to mutate the original [List].
  assert(length == keyValues.length);
  for (var i = 0; i < length; i += 1) {
    this[i] = keyValues[i].value;
  }
}