comparingWith<T, U> static method

Comparator<T> comparingWith<T, U>(
  1. U keyExtractor(
    1. T
    ),
  2. Comparator<U> keyComparator
)

Creates a comparator based on a key extractor and a custom comparator for the key.

Allows sorting by derived values that require special ordering rules.


Example

class Item {
  final String name;
  Item(this.name);
}

final byLastCharDesc = Comparator.comparingWith<Item, String>(
  (item) => item.name[item.name.length - 1],
  Comparator.reverseOrder(),
);

final items = [Item('Box'), Item('Ball'), Item('Bat')];
items.sort(byLastCharDesc.compare);
print(items.map((i) => i.name)); // [Bat, Box, Ball]

Implementation

static Comparator<T> comparingWith<T, U>(U Function(T) keyExtractor, Comparator<U> keyComparator) => _ComparingComparator(keyExtractor, keyComparator);