min Of Or Null
Начиная с Kotlin: 1.4
inline fun <T> Sequence<T>.minOfOrNull(selector: (T) -> Double): Double?
inline fun <T> Sequence<T>.minOfOrNull(selector: (T) -> Float): Float?
Возвращает наименьшее значение среди всех значений, полученных в результате применения функции селектор к каждому элементу последовательности, или null, если последовательность пуста.
Если какое-либо из значений, полученных в результате применения функции селектор, равно NaN, возвращаемым результатом будет NaN.
Операция является терминальной.
Примеры
import kotlin.math.*
import kotlin.test.*
fun main() {
//sampleStart
data class Rectangle(val width: Double, val height: Double) {
val aspectRatio: Double get() = if (height != 0.0) width / height else Double.NaN
}
// The largest and smallest width-to-height ratios
val rectangles = listOf(
Rectangle(15.0, 10.0),
Rectangle(25.0, 20.0),
Rectangle(40.0, 30.0),
)
println(rectangles.maxOf { it.aspectRatio }) // 1.5
println(rectangles.minOf { it.aspectRatio }) // 1.25
// Aspect ratio of a point (0.0 by 0.0) is NaN, hence the result is NaN
val rectanglesAndPoint = rectangles + Rectangle(0.0, 0.0)
println(rectanglesAndPoint.maxOf { it.aspectRatio }) // NaN
println(rectanglesAndPoint.minOf { it.aspectRatio }) // NaN
val emptyList = emptyList<Rectangle>()
// maxOf() and minOf() throw if the collection is empty
// emptyList.maxOf { it.aspectRatio } // will fail with NoSuchElementException
// emptyList.minOf { it.aspectRatio } // will fail with NoSuchElementException
// maxOfOrNull() and minOfOrNull() return null if the collection is empty
println(emptyList.maxOfOrNull { it.aspectRatio }) // null
println(emptyList.minOfOrNull { it.aspectRatio }) // null
//sampleEnd
}
inline fun <T, R : Comparable<R>> Sequence<T>.minOfOrNull(selector: (T) -> R): R?
Возвращает наименьшее значение среди всех значений, полученных в результате применения функции селектор к каждому элементу последовательности, или null, если последовательность пуста.
Если несколько элементов дают минимальное значение, эта функция возвращает первое из этих значений.
Операция является терминальной.
Примеры
import kotlin.math.*
import kotlin.test.*
fun main() {
//sampleStart
// The length of the longest and shortest names
val names = listOf("Alice", "Bob", "Carol")
println(names.maxOf { it.length }) // 5
println(names.minOf { it.length }) // 3
val emptyList = emptyList<String>()
// maxOf() and minOf() throw if the collection is empty
// emptyList.maxOf { it.length } // will fail with NoSuchElementException
// emptyList.minOf { it.length } // will fail with NoSuchElementException
// maxOfOrNull() and minOfOrNull() return null if the collection is empty
println(emptyList.maxOfOrNull { it.length }) // null
println(emptyList.minOfOrNull { it.length }) // null
//sampleEnd
}
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.sequences/min-of-or-null.html