maxOfWithOrNull

inline fun <R> CharSequence.maxOfWithOrNull(comparator: Comparator<in R>, selector: (Char) -> R): R?(source)

Returns the largest value according to the provided comparator among all values produced by selector function applied to each character in the char sequence or null if the char sequence is empty.

If multiple characters produce the maximal value, this function returns the first of those values.

Since Kotlin

1.4

Samples

import kotlin.math.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   data class Book(val title: String, val publishYear: Int, val rating: Double)

// A custom Comparator that orders strings by their length
val lengthComparator = compareBy<String> { it.length }

// The longest and shortest book titles
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 }) // Silver Bullet
println(books.minOfWith(lengthComparator) { it.title }) // Red Sand

val emptyList = listOf<Book>()

// maxOfWith() and minOfWith() throw if the collection is empty
// emptyList.maxOfWith(lengthComparator) { it.title } // will fail with NoSuchElementException
// emptyList.minOfWith(lengthComparator) { it.title } // will fail with NoSuchElementException

// maxOfWithOrNull() and minOfWithOrNull() return null if the collection is empty
println(emptyList.maxOfWithOrNull(lengthComparator) { it.title }) // null
println(emptyList.minOfWithOrNull(lengthComparator) { it.title }) // null 
   //sampleEnd
}