DEV Community

loizenai
loizenai

Posted on

Kotlin Array find the Smallest Element – min() minBy() minWith() methods

https://grokonez.com/kotlin/kotlin-array-find-smallest-element-min-minby-minwith-methods

Kotlin Array find the Smallest Element – min() minBy() minWith() methods

In the tutorial, JavaSampleApproach will show how to use Kotlin Array methods min(), minBy(), minWith() to find the smallest element in a Kotlin Array.

I. min() method

Kotlin Array method min() is used to returns the smallest element or null if there are no elements. If any of elements is NaN, it returns NaN.

Method signatures:

//1. 
public fun Array<out Double>.min(): Double?

//2. 
public fun Array<out Float>.min(): Float?

Example:


package com.javasampleapproach.kotlin.array

fun main(args : Array){
    val simpleArray = arrayOf(55.4, 20.0, 99.99, 1.99, 23.0, 34.2, 88.0, 72.1, 61.2, 43.9)
     
    // public fun Array.min(): Double?
    val largestElement = simpleArray.max()
    println(largestElement)
    // ->
    /*
        1.99
    */  
}

min() with Comparable

-> Implement Comparable for Kotlin Array object.

Method signature:

https://grokonez.com/kotlin/kotlin-array-find-smallest-element-min-minby-minwith-methods

Kotlin Array find the Smallest Element – min() minBy() minWith() methods

Top comments (0)