maxByOrNull

inline fun <T, R : Comparable<R>> Array<out T>.maxByOrNull(selector: (T) -> R): T?(source)
inline fun <R : Comparable<R>> ByteArray.maxByOrNull(selector: (Byte) -> R): Byte?(source)
inline fun <R : Comparable<R>> ShortArray.maxByOrNull(selector: (Short) -> R): Short?(source)
inline fun <R : Comparable<R>> IntArray.maxByOrNull(selector: (Int) -> R): Int?(source)
inline fun <R : Comparable<R>> LongArray.maxByOrNull(selector: (Long) -> R): Long?(source)
inline fun <R : Comparable<R>> FloatArray.maxByOrNull(selector: (Float) -> R): Float?(source)
inline fun <R : Comparable<R>> DoubleArray.maxByOrNull(selector: (Double) -> R): Double?(source)
inline fun <R : Comparable<R>> BooleanArray.maxByOrNull(selector: (Boolean) -> R): Boolean?(source)
inline fun <R : Comparable<R>> CharArray.maxByOrNull(selector: (Char) -> R): Char?(source)
inline fun <T, R : Comparable<R>> Iterable<T>.maxByOrNull(selector: (T) -> R): T?(source)

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

Since Kotlin

1.4

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val nameToAge = listOf("Alice" to 42, "Bob" to 28, "Carol" to 51)
val oldestPerson = nameToAge.maxByOrNull { it.second }
println(oldestPerson) // (Carol, 51)

val emptyList = emptyList<Pair<String, Int>>()
val emptyMax = emptyList.maxByOrNull { it.second }
println(emptyMax) // null 
   //sampleEnd
}

inline fun <K, V, R : Comparable<R>> Map<out K, V>.maxByOrNull(selector: (Map.Entry<K, V>) -> R): Map.Entry<K, V>?(source)

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

Since Kotlin

1.4

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val nameToAge = listOf("Alice" to 42, "Bob" to 28, "Carol" to 51)
val oldestPerson = nameToAge.maxByOrNull { it.second }
println(oldestPerson) // (Carol, 51)

val emptyList = emptyList<Pair<String, Int>>()
val emptyMax = emptyList.maxByOrNull { it.second }
println(emptyMax) // null 
   //sampleEnd
}