Hi, I have a list of Booleans, and I need to know ...
# getting-started
n
Hi, I have a list of Booleans, and I need to know the index of all the ones that are false, so a list of indexes. What is the best way to achieve this?
e
not sure what you've tried already, but most direct way is just fine
Copy code
list.indices.filter { !list[it] }
๐Ÿ™ 1
๐Ÿ‘ 1
n
Thanks, I had tried
.indexOf()
but was getting nowhere.
s
I think
filterIndexed
exists
๐Ÿ‘ 1
e
@Starr that will return a list of the original booleans, which isn't very useful
Copy code
list.mapIndexedNotNull { i, bool ->
    if (bool) null else i
}
would work but is not necessary when first one suffices
๐Ÿ‘ 1
k
An alternative:
Copy code
list.withIndex().filter { !it.value }.map { it.index }
This may be more performant than ephemient's first solution if the list is large and not random-access.
n
Thanks, the list has 28 Booleans always. I assume that is a small list! ๐Ÿ™‚
k
But is it random access? If so, you might as well use ephemient's solution.
n
what does random-access mean?
k
It means that retrieving the value of list[n] takes constant time, no matter what value n is. Examples of random-access lists include
ArrayList
and the type of list you get by calling
listOf()
. Examples of non-random-access lists include
LinkedList
and generally any list where finding the value of
list[n]
requires you to start from index 0 and iterate the list through each element until you get to element n.
n
Thanks for this, then it is random-access.
e
Klitos, that's less performance than my second solution. Nat, almost all lists are RandomAccess. IMO it was a design mistake to put non-random access lists in the same interface, but that's how the Java API was designed
๐Ÿ‘ 2
a
@ephemient Hi, is there a better way to check performance in intellij of a given solution than this code ? :
Copy code
val list:List<Boolean> =BooleanArray(100){Random.nextBoolean()}.toList()
val start: Long = System.nanoTime()
list.mapIndexedNotNull { i, bool ->
    if (bool) null else i
}
val end: Long = System.nanoTime();
println(end - start)
e
don't benchmark like that, use JMH (or kotlinx.benchmark which wraps JMH on JVM)
๐Ÿ‘ 1
a
Thanks!
n
Another advantage of the
mapIndexedNotNull
approach is that you do not need a named list. Of course, this does not matter if you anyway wrap it into a function.