Returns the largest value according to the provided comparator among all values produced by selector function applied to each element in the sequence or null
if the sequence is empty.
If multiple elements produce the maximal value, this function returns the first of those values.
The operation is terminal.
Since Kotlin
1.4Samples
import kotlin.math.*
import kotlin.test.*
fun main() {
data class Book(val title: String, val publishYear: Int, val rating: Double)
val lengthComparator = compareBy<String> { it.length }
val books = listOf(
Book("Red Sand", 2004, 3.5),
Book("Silver Bullet", 2009, 4.4),
Book("Clear Water", 2018, 4.1),
Book("Night Sky", 2023, 3.8)
)
println(books.maxOfWith(lengthComparator) { it.title })
println(books.minOfWith(lengthComparator) { it.title })
val emptyList = listOf<Book>()
println(emptyList.maxOfWithOrNull(lengthComparator) { it.title })
println(emptyList.minOfWithOrNull(lengthComparator) { it.title })
}
Target: JVMRunning on v.2.1.20