# Returning an Index of a Collection based on criteria

**URL:** <https://discuss.kotlinlang.org/t/returning-an-index-of-a-collection-based-on-criteria/9691>\
**Category:** Language Design\
**Created:** [October 4, 2018, 6:04pm UTC](https://discuss.kotlinlang.org/t/returning-an-index-of-a-collection-based-on-criteria/9691 "2018-10-04T18:04:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wonderbeef](https://avatars.discourse-cdn.com/v4/letter/w/22d042/32.png) [@wonderbeef](https://discuss.kotlinlang.org/u/wonderbeef)\
**Post date:** [October 4, 2018, 6:04pm UTC](https://discuss.kotlinlang.org/t/returning-an-index-of-a-collection-based-on-criteria/9691/1 "2018-10-04T18:04:54Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![al3c](https://avatars.discourse-cdn.com/v4/letter/a/e47774/32.png) [@al3c](https://discuss.kotlinlang.org/u/al3c)\
**Post date:** [October 4, 2018, 7:08pm UTC](https://discuss.kotlinlang.org/t/returning-an-index-of-a-collection-based-on-criteria/9691/2 "2018-10-04T19:08:38Z")

</div>

`indexOfFirst` does that:

> **[indexOfFirst - Kotlin Programming Language](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.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [October 6, 2018, 2:31pm UTC](https://discuss.kotlinlang.org/t/returning-an-index-of-a-collection-based-on-criteria/9691/3 "2018-10-06T14:31:27Z")

</div>

@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 }

```
