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