The maxByOrNull() extension function in Kotlin returns the first element yielding the largest value of the given function, or null if there are no elements.
The syntax of Set.maxByOrNull() extension function is:
fun <T, R : Comparable<R>> Set<T>.maxByOrNull(selector: (T) -> R): T?
This maxByOrNull() extension function of Set returns the first element yielding the largest 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.maxByOrNull() returns value of type T?
.
Using maxByOrNull() to find the maximum element in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxNumber = numbers.maxByOrNull { it }
println(maxNumber)
}
5
Using maxByOrNull() to find the string with the maximum length in a set.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val longestString = strings.maxByOrNull { it.length }
println(longestString)
}
three
Using maxByOrNull() to find the custom object with the maximum 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 oldestPerson = people.maxByOrNull { it.age }
println(oldestPerson)
}
Person(name=Charlie, age=35)
In this Kotlin tutorial, we learned about maxByOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.