maxBy method

T? maxBy(
  1. Comparator<T> comparator
)

Returns the maximum value based on the comparator function. If collection is empty this returns null.

Example:

[90, 10, 20, 30].maxBy((a, b) => a.compareTo(b)); // 90
persons.maxBy((a, b) => a.age.compareTo(b.age));  // the oldest person

Implementation

T? maxBy(Comparator<T> comparator) {
  if (isEmpty) {
    return null;
  }
  return reduce(
      (value, element) => comparator(value, element) > 0 ? value : element);
}