The maxOf() extension function in Kotlin returns the largest value among all values produced by the selector function applied to each element in the collection.
The syntax of Set.maxOf() extension function is:
fun <T> Set<T>.maxOf(selector: (T) -> Double): Double
This maxOf() extension function of Set returns the largest 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.maxOf() returns value of type Double
.
Using maxOf() to find the maximum value among integers in a set transformed to double.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxValue = numbers.maxOf { it.toDouble() }
println(maxValue)
}
5.0
Using maxOf() to find the maximum length among strings in a set.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val maxLength = strings.maxOf { it.length.toDouble() }
println(maxLength)
}
5.0
Using maxOf() to find the maximum 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 maxAge = people.maxOf { it.age.toDouble() }
println(maxAge)
}
35.0
In this Kotlin tutorial, we learned about maxOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.