The maxOfOrNull() extension function in Kotlin returns the largest value among all values produced by the selector function applied to each element in the collection, or null if there are no elements.
The syntax of Set.maxOfOrNull() extension function is:
fun <T> Set<T>.maxOfOrNull(selector: (T) -> Double): Double?
This maxOfOrNull() extension function of Set returns the largest value among all values produced by selector function applied to each element in the collection or null if there are no elements.
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns a Double value to be compared. |
Set.maxOfOrNull() returns value of type Double?
.
Using maxOfOrNull() to find the maximum value among integers in a set transformed to double, or null if the set is empty.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxValue = numbers.maxOfOrNull { it.toDouble() }
println(maxValue)
}
5.0
Using maxOfOrNull() to find the maximum length among strings in a set, or null if the set is empty.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val maxLength = strings.maxOfOrNull { it.length.toDouble() }
println(maxLength)
}
5.0
Using maxOfOrNull() to find the maximum age among custom objects in a set, 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 maxAge = people.maxOfOrNull { it.age.toDouble() }
println(maxAge)
}
35.0
Using maxOfOrNull() to handle an empty set and return null.
For example,
fun main() {
val emptySet = emptySet<Int>()
val maxValue = emptySet.maxOfOrNull { it.toDouble() }
println(maxValue)
}
null
In this Kotlin tutorial, we learned about maxOfOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.