Returning an Index of a Collection based on criteria


#1

Kotlin has some pretty cool functions for collections. However, I have come across a problem in which the solution is not apparent to me.

I have a List of Objects. Those Objects have an ID field which coincides with a SQLite database. SQL operations are performed on the database, and a new list is generated. How can the index of an item from the new list be found based on the “ID” field (or any other field for that matter)?

the Collection.find{} function return the object, but not the index.


#2

indexOfFirst does that:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index-of-first.html

For example list.indexOfFirst{ it.id = 123 } find the index of the first element whose id is 123.

There’s also indexOfLast in case you have more than one.


#3

@al3c suggestion is fine if you do not need to repeatedly do the search. If you are going to search a lot then you probably want to create a map from ID to index for performance reasons. You are trading extra memory for improved lookup performance.

It is a little more difficult because you asked for index instead of the object but something like this should work:

val map = yourList
    .withIndex()
    .associate { it.value.id to it.index }