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) -> nums[i] == max }) ?: -1
is there a better way?
indexOf() to Check if Element is in List. If the element is present in the list, then list. indexOf(element), will return a non-negative integer, else it returns -1. We can use this behavior to check if element is present in the list or not.
Kotlin – Index of Substring in String To find index of substring in this string in Kotlin, call indexOf() method on this string, and pass the substring as argument. String. indexOf() returns an integer representing the index of first occurrence of the match for the given substring.
For retrieving an element at a specific position, there is the function elementAt() . Call it with the integer number as an argument, and you'll receive the collection element at the given position. The first element has the position 0 , and the last one is (size - 1) .
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.
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())
If you want to find the item based on some predicate, then you can use indexOfFirst
and indexOfLast
extension functions.
val strings = arrayOf("hello","world","hello")
val firstHelloIndex = strings.indexOfFirst { it == "hello" }
val lastHelloIndex = strings.indexOfLast { it == "hello" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With