Kotlin Set maxByOrNull()
Syntax & Examples
Set.maxByOrNull() extension function
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.
Syntax of Set.maxByOrNull()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Return Type
Set.maxByOrNull() returns value of type T?
.
✐ Examples
1 Finding the maximum element by a property in a set of integers
Using maxByOrNull() to find the maximum element in a set of integers.
For example,
- Create a set of integers.
- Use maxByOrNull() with a selector function that returns the element itself.
- Print the resulting element.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxNumber = numbers.maxByOrNull { it }
println(maxNumber)
}
Output
5
2 Finding the string with the maximum length in a set
Using maxByOrNull() to find the string with the maximum length in a set.
For example,
- Create a set of strings.
- Use maxByOrNull() with a selector function that returns the length of each string.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three")
val longestString = strings.maxByOrNull { it.length }
println(longestString)
}
Output
three
3 Finding the custom object with the maximum age in a set
Using maxByOrNull() to find the custom object with the maximum age in a set.
For example,
- Create a data class.
- Create a set of custom objects.
- Use maxByOrNull() with a selector function that returns the age of each object.
- Print the resulting object.
Kotlin Program
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)
}
Output
Person(name=Charlie, age=35)
Summary
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.