indexOf in Kotlin Arrays

前端 未结 2 1352
星月不相逢
星月不相逢 2021-01-07 18:01

How do I get the index of a value from a Kotlin array?

My best solution right now is using:

val max = nums.max()
val maxIdx = nums.indices.find({ (i)         


        
相关标签:
2条回答
  • 2021-01-07 18:42

    If you want to get the index of the maximum element you can use 'maxBy' function:

    val maxIdx = nums.indices.maxBy { nums[it] } ?: -1
    

    It is more efficient since it will traverse the array only once.

    0 讨论(0)
  • 2021-01-07 18:47

    With current Kotlin (1.0) you can use indexOf() extension function on arrays:

    val x = arrayOf("happy","dancer","jumper").indexOf("dancer")
    

    All extension functions for arrays are found in the api reference.

    In your example:

    val maxIdx = nums.indexOf(nums.max())
    
    0 讨论(0)
提交回复
热议问题