minOfWith

inline fun <T, R> Sequence<T>.minOfWith(comparator: Comparator<in R>, selector: (T) -> R): R(source)

Returns the smallest value according to the provided comparator among all values produced by selector function applied to each element in the sequence.

If multiple elements produce the minimal value, this function returns the first of those values.

Since Kotlin

1.4

Throws

if the sequence is empty.

The operation is terminal.

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
}