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