0

In kotlin, I have a data class like this:

data class MyModel (
    val key: String,
    val myValue: String
)

I have an ArrayList of above model:

val myList: ArrayList<MyModel>

I don't know how to get the index of an element by passing the key:

fun getPosition(key: String): Int = myList.indexOf(/* what to do here? */)

----edit----

Assume that keys are unique.

4
  • what if there are multiple entries with the same key? Commented Jun 24, 2019 at 9:28
  • the keys are unique in the required case Commented Jun 24, 2019 at 9:32
  • might be easier to work with a map then Commented Jun 24, 2019 at 9:36
  • I am implementing ItemKeyProvider in RecyclerView in android, for that I needed to know this. Commented Jun 24, 2019 at 9:38

1 Answer 1

9

You can use indexOfFirst which receive a functional parameter:

fun getPosition(key: String): Int = myList.indexOfFirst { it.key == key }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.