The maxWithOrNull() extension function in Kotlin returns the first element having the largest value according to the provided comparator, or null if there are no elements.
The syntax of Set.maxWithOrNull() extension function is:
fun <T> Set<T>.maxWithOrNull(comparator: Comparator<in T>): T?
This maxWithOrNull() extension function of Set returns the first element having the largest value according to the provided comparator or null if there are no elements.
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to compare the elements. |
Set.maxWithOrNull() returns value of type T?
.
Using maxWithOrNull() to find the maximum element in a set of integers with a custom comparator, or null if the set is empty.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxNumber = numbers.maxWithOrNull(compareBy { it })
println(maxNumber)
}
5
Using maxWithOrNull() to find the maximum string in a set based on length with a custom comparator, or null if the set is empty.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val maxLengthString = strings.maxWithOrNull(compareBy { it.length })
println(maxLengthString)
}
three
Using maxWithOrNull() to find the maximum custom object in a set based on a property with a custom comparator, 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 oldestPerson = people.maxWithOrNull(compareBy { it.age })
println(oldestPerson)
}
Person(name=Charlie, age=35)
Using maxWithOrNull() to handle an empty set and return null with a custom comparator.
For example,
fun main() {
val emptySet = emptySet<Int>()
val maxNumber = emptySet.maxWithOrNull(compareBy { it })
println(maxNumber)
}
null
In this Kotlin tutorial, we learned about maxWithOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.