https://kotlinlang.org logo
Title
n

Nat Strangerweather

06/11/2022, 7:13 PM
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

ephemient

06/11/2022, 7:19 PM
not sure what you've tried already, but most direct way is just fine
list.indices.filter { !list[it] }
:thank-you: 1
👍 1
n

Nat Strangerweather

06/11/2022, 7:20 PM
Thanks, I had tried
.indexOf()
but was getting nowhere.
s

Starr

06/11/2022, 7:20 PM
I think
filterIndexed
exists
👍 1
e

ephemient

06/11/2022, 7:25 PM
@Starr that will return a list of the original booleans, which isn't very useful
list.mapIndexedNotNull { i, bool ->
    if (bool) null else i
}
would work but is not necessary when first one suffices
👍 1
k

Klitos Kyriacou

06/12/2022, 10:38 AM
An alternative:
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

Nat Strangerweather

06/12/2022, 10:43 AM
Thanks, the list has 28 Booleans always. I assume that is a small list! 🙂
k

Klitos Kyriacou

06/12/2022, 10:46 AM
But is it random access? If so, you might as well use ephemient's solution.
n

Nat Strangerweather

06/12/2022, 10:48 AM
what does random-access mean?
k

Klitos Kyriacou

06/12/2022, 10:53 AM
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

Nat Strangerweather

06/12/2022, 10:58 AM
Thanks for this, then it is random-access.
e

ephemient

06/12/2022, 8:09 PM
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

Anouar di Kali

06/12/2022, 9:10 PM
@ephemient Hi, is there a better way to check performance in intellij of a given solution than this 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

ephemient

06/12/2022, 10:26 PM
don't benchmark like that, use JMH (or kotlinx.benchmark which wraps JMH on JVM)
👍 1
a

Anouar di Kali

06/12/2022, 10:41 PM
Thanks!
n

nkiesel

06/13/2022, 6:55 PM
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.