The minByOrNull() extension function in Kotlin returns the first element yielding the smallest value of the given function, or null if there are no elements.
The syntax of Set.minByOrNull() extension function is:
fun <T, R : Comparable<R>> Set<T>.minByOrNull(selector: (T) -> R): T?
This minByOrNull() extension function of Set returns the first element yielding the smallest value of the given function or null if there are no elements.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Set.minByOrNull() returns value of type T?
.
Using minByOrNull() to find the minimum element in a set of integers.
For example,
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minNumber = numbers.minByOrNull { it }
println(minNumber)
}
1
Using minByOrNull() to find the string with the minimum length in a set.
For example,
fun main() {
val strings = setOf("apple", "pear", "banana")
val shortestString = strings.minByOrNull { it.length }
println(shortestString)
}
pear
Using minByOrNull() to find the custom object with the minimum age in a set.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val youngestPerson = people.minByOrNull { it.age }
println(youngestPerson)
}
Person(name=Bob, age=25)
Using minByOrNull() to handle an empty set and return null.
For example,
fun main() {
val emptySet = emptySet<Int>()
val minNumber = emptySet.minByOrNull { it }
println(minNumber)
}
null
In this Kotlin tutorial, we learned about minByOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.