minBy
Returns the first character yielding the smallest value of the given selector function.
If there are multiple equal minimal values returned by the selector function, this function returns the first of characters corresponding to these values.
Note that the function selector is not invoked when the char sequence contains zero or one characters because in these cases it is clear which character to return without invoking the selector. Therefore it's recommended to avoid relying on side effects being performed by the selector function on each character.
Since Kotlin
1.7Throws
if the char sequence is empty.
Samples
import kotlin.math.*
import kotlin.test.*
fun main() {
//sampleStart
val strings = listOf("abcd", "abc", "ab", "de", "abcde")
val longestString = strings.maxBy { it.length }
println(longestString) // abcde
val shortestString = strings.minBy { it.length }
println(shortestString) // ab
val emptyList = emptyList<String>()
// maxBy() and minBy() throw if the collection is empty
// emptyList.maxBy { it.length } // will fail with NoSuchElementException
// emptyList.minBy { it.length } // will fail with NoSuchElementException
// maxByOrNull() and minByOrNull() return null if the collection is empty
println(emptyList.maxByOrNull { it.length }) // null
println(emptyList.minByOrNull { it.length }) // null
//sampleEnd
}
Deprecated
Warning since 1.4
Error since 1.5
Hidden since 1.6
Use minByOrNull instead.
Replace with
this.minByOrNull(selector)
Content copied to clipboard