I want to get index list as follows.
val a = booleanArrayOf(true,false,true,false)
above code, True number is two. -> indexList = {0, 2} how to get indexList in Kotlin.
The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Syntax : public int IndexOf(Object o) obj : The element to search for.
An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
The simple approach to filtering a MutableList in-place is to iterate through the list using an iterator and remove the list elements using iterator's remove() function. Please note that ConcurrentModificationException will be thrown if remove() function of MutableList is used instead.
You could use mapIndexed()
to get the index and the value of each element, convert to either the index or null, and then remove the nulls...
val b: List<Int> = a.mapIndexed { i, b -> if (b) i else null }.filterNotNull().toList()
Another way would be to use the withIndex()
function, filter the values that are true, and map the resulting pairs to the index value. This might be a bit clearer.
val c: List<Int> = a.withIndex().filter { it.value }.map { it.index }
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