Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get index list in arrayList filter

Tags:

kotlin

filter

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.

like image 848
Taehyung Kim Avatar asked Jun 07 '18 00:06

Taehyung Kim


People also ask

How do you find the index of an ArrayList?

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.

How do I get an element from an ArrayList?

An element can be retrieved from the ArrayList in Java by using the java. util. ArrayList. get() method.

How do you find the index of a particular element in a list in Java?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

How do you filter a mutable list?

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.


1 Answers

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 }
like image 152
Todd Avatar answered Oct 14 '22 15:10

Todd