Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf in Kotlin Arrays

Tags:

arrays

kotlin

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?

like image 737
talloaktrees Avatar asked Dec 24 '13 13:12

talloaktrees


People also ask

How do you use Kotlin indexOf?

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.

How do you find the index of a string in Kotlin?

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.

How do you access list elements in Kotlin?

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) .


3 Answers

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.

like image 122
Nik Avatar answered Oct 19 '22 07:10

Nik


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())
like image 28
2 revs, 2 users 63% Avatar answered Oct 19 '22 06:10

2 revs, 2 users 63%


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" }
like image 1
mightyWOZ Avatar answered Oct 19 '22 06:10

mightyWOZ