Kotlin Set maxOf()
Syntax & Examples
Set.maxOf() extension function
The maxOf() extension function in Kotlin returns the largest value among all values produced by the selector function applied to each element in the collection.
Syntax of Set.maxOf()
The syntax of Set.maxOf() extension function is:
fun <T> Set<T>.maxOf(selector: (T) -> Double): Double
This maxOf() extension function of Set returns the largest value among all values produced by selector function applied to each element in the collection.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns a Double value to be compared. |
Return Type
Set.maxOf() returns value of type Double
.
✐ Examples
1 Finding the maximum value among integers transformed to double
Using maxOf() to find the maximum value among integers in a set transformed to double.
For example,
- Create a set of integers.
- Use maxOf() with a selector function that transforms each integer to double.
- Print the resulting maximum value.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val maxValue = numbers.maxOf { it.toDouble() }
println(maxValue)
}
Output
5.0
2 Finding the maximum length of strings
Using maxOf() to find the maximum length among strings in a set.
For example,
- Create a set of strings.
- Use maxOf() with a selector function that returns the length of each string as a double.
- Print the resulting maximum length.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three")
val maxLength = strings.maxOf { it.length.toDouble() }
println(maxLength)
}
Output
5.0
3 Finding the maximum age among custom objects
Using maxOf() to find the maximum age among custom objects in a set.
For example,
- Create a data class.
- Create a set of custom objects.
- Use maxOf() with a selector function that returns the age of each object as a double.
- Print the resulting maximum age.
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 maxAge = people.maxOf { it.age.toDouble() }
println(maxAge)
}
Output
35.0
Summary
In this Kotlin tutorial, we learned about maxOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.