14

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.

1 Answer 1

34

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Todd, I am using as below example val indexList: List<Int> = yourList.withIndex().filter { (!it.value.your_custom_object!!.keyName.equals("") && it.value.your_custom_object!!.keyName!!.equals( "some_value", ignoreCase = true )) }.map { it.index }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.