Kotlin Array.minOf() Function
In Kotlin, the Array.minOf()
function is used to find the minimum element among the elements of the given array or any other collection. It returns the smallest element based on the natural order or a custom comparison function.
This function is handy when you need to determine the minimum value in an array or a collection without manually iterating through the elements.
In this tutorial, we’ll explore the syntax of the Array.minOf()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.minOf()
function is as follows:
inline fun <T> Array<out T>.minOf(
selector: (T) -> Double
): Double
inline fun <T> Array<out T>.minOf(
selector: (T) -> Float
): Float
inline fun <T, R : Comparable<R>> Array<out T>.minOf(
selector: (T) -> R
): R
The minOf()
function takes a selector function and returns the minimum of the elements based on comparison with the selector function values for each of the elements in the array.
Examples for Array.minOf() Function
1. Finding the minimum value in an Integer array
In this example, we’ll take an array with integer values in numbersArray
, and use the minOf()
function to find the minimum number and print it to output.
Kotlin Program
fun main() {
val numbersArray = arrayOf(5, 2, 8, 1, 7, 3)
// Using minOf() to find the minimum element in the array
val minimumValue = numbersArray.minOf { it }
// Printing the original array and the result
println("Numbers Array\n${numbersArray.contentToString()}\n")
println("Minimum Value\n$minimumValue")
}
Output
Numbers Array
[5, 2, 8, 1, 7, 3]
Minimum Value
1
2. Finding the least length of element in given string array using Array.minOf() function
In this example, we’ll take an array with string values in stringsArray
, and use the minOf()
function to find the length of smallest string element. The selector shall be the string length.
Kotlin Program
fun main() {
val stringsArray = arrayOf("apple", "banana", "fig", "cherry")
// Using minOf() to find the smallest string length in the array
val smallestStringLength = stringsArray.minOf { it.length }
// Printing the original array and the result
println("Given Array\n${stringsArray.contentToString()}\n")
println("Smallest length of string element in array\n$smallestStringLength")
}
Output
Given Array
[apple, banana, fig, cherry]
Smallest length of string element in array
3
Summary
In this tutorial, we’ve covered the Array.minOf()
function in Kotlin, its syntax, and how to use it to find the minimum element.