max<T> static method

T max<T>(
  1. Iterable<T> list, {
  2. Comparable by(
    1. T
    )?,
})

Returns the element of list with the largest value of by (or the largest element itself when by is null and T is Comparable).

Implementation

static T max<T>(Iterable<T> list, {Comparable Function(T)? by}) {
  if (list.isEmpty) throw ArgumentError('list must not be empty');
  T? best;
  Comparable? bestKey;
  for (final v in list) {
    final k = by != null ? by(v) : (v as Comparable);
    if (bestKey == null || k.compareTo(bestKey) > 0) {
      bestKey = k;
      best = v;
    }
  }
  return best as T;
}