Kotlin Array.maxOf()

Kotlin Array.maxOf() Function

In Kotlin, the Array.maxOf() function is used to find the maximum element among the elements of the given array or any other collection. It returns the largest element based on the natural order or a custom comparison function.

This function is handy when you need to determine the maximum value in an array or a collection without manually iterating through the elements.

In this tutorial, we’ll explore the syntax of the Array.maxOf() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.maxOf() function is as follows:

inline fun <T> Array<out T>.maxOf(
    selector: (T) -> Double
): Double

inline fun <T> Array<out T>.maxOf(
    selector: (T) -> Float
): Float

inline fun <T, R : Comparable<R>> Array<out T>.maxOf(
    selector: (T) -> R
): R

The maxOf() function takes a selector function and returns the maximum of the elements based on comparison with the selector function values obtained for each of the elements in the array.

Examples for Array.maxOf() Function

1. Finding the maximum value in an Integer array

In this example, we’ll take an array with integer values in numbersArray, and use the maxOf() function to find the maximum number and print it to output.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(5, 2, 8, 1, 7, 3)

    // Using maxOf() to find the maximum element in the array
    val maximumValue = numbersArray.maxOf { it }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.contentToString()}\n")
    println("Maximum Value\n$maximumValue")
}

Output

Numbers Array
[5, 2, 8, 1, 7, 3]

Maximum Value
8

2. Finding the string value with largest length in given array using Array.maxOf() function

In this example, we’ll take an array with string values in stringsArray, and use the maxOf() function to find the string element with largest length. The selector shall be the string length.

Kotlin Program

fun main() {
    val stringsArray = arrayOf("apple", "banana", "fig", "cherry")

    // Using maxOf() to find the largest string length in the array
    val largestStringLength = stringsArray.maxOf { it.length }

    // Printing the original array and the result
    println("Given Array\n${stringsArray.contentToString()}\n")
    println("Largest length of string element in array\n$largestStringLength")
}

Output

[apple, banana, fig, cherry]

Largest length of string element in array
6

Summary

In this tutorial, we’ve covered the Array.maxOf() function in Kotlin, its syntax, and how to use it to find the maximum element.