The minOf() extension function in Kotlin returns the smallest value among all values produced by the selector function applied to each element in the collection.
The syntax of Set.minOf() extension function is:
fun <T> Set<T>.minOf(selector: (T) -> Double): Double
This minOf() extension function of Set returns the smallest value among all values produced by selector function applied to each element in the collection.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns a Double value to be compared. |
Set.minOf() returns value of type Double
.
Using minOf() to find the minimum value among integers in a set transformed to double.
For example,
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minValue = numbers.minOf { it.toDouble() }
println(minValue)
}
1.0
Using minOf() to find the minimum length among strings in a set.
For example,
fun main() {
val strings = setOf("apple", "pear", "banana")
val minLength = strings.minOf { it.length.toDouble() }
println(minLength)
}
4.0
Using minOf() to find the minimum age among custom objects 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 minAge = people.minOf { it.age.toDouble() }
println(minAge)
}
25.0
In this Kotlin tutorial, we learned about minOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.