maxBy<R extends Comparable> method Null safety

KtMapEntry<K, V>? maxBy<R extends Comparable>(
  1. R selector(
    1. KtMapEntry<K, V>
    )
)

Returns the first entry yielding the largest value of the given function or null if there are no entries.

Implementation

KtMapEntry<K, V>? maxBy<R extends Comparable>(
    R Function(KtMapEntry<K, V>) selector) {
  final i = iterator();
  if (!iterator().hasNext()) return null;
  KtMapEntry<K, V> maxElement = i.next();
  R maxValue = selector(maxElement);
  while (i.hasNext()) {
    final e = i.next();
    final v = selector(e);
    if (maxValue.compareTo(v) < 0) {
      maxElement = e;
      maxValue = v;
    }
  }
  return maxElement;
}