The minWithOrNull() extension function in Kotlin returns the first element having the smallest value according to the provided comparator, or null if there are no elements.
The syntax of Set.minWithOrNull() extension function is:
fun <T> Set<T>.minWithOrNull(comparator: Comparator<in T>): T?
This minWithOrNull() extension function of Set returns the first element having the smallest value according to the provided comparator or null if there are no elements.
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to compare the elements. |
Set.minWithOrNull() returns value of type T?
.
Using minWithOrNull() to find the minimum element in a set of integers with a custom comparator, or null if the set is empty.
For example,
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minNumber = numbers.minWithOrNull(compareBy { it })
println(minNumber)
}
1
Using minWithOrNull() to find the minimum string in a set based on length with a custom comparator, or null if the set is empty.
For example,
fun main() {
val strings = setOf("apple", "pear", "banana")
val shortestString = strings.minWithOrNull(compareBy { it.length })
println(shortestString)
}
pear
Using minWithOrNull() to find the minimum custom object in a set based on a property with a custom comparator, or null if the set is empty.
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.minWithOrNull(compareBy { it.age })
println(youngestPerson)
}
Person(name=Bob, age=25)
Using minWithOrNull() to handle an empty set and return null with a custom comparator.
For example,
fun main() {
val emptySet = emptySet<Int>()
val minNumber = emptySet.minWithOrNull(compareBy { it })
println(minNumber)
}
null
In this Kotlin tutorial, we learned about minWithOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.