Search code examples
javakotlinkeyvaluepair

How can I retrieve a value from a list of key/value pairs with the key from a given pair?


I have the following list of pairs

val mItemArray : ArrayList<Pair<Long, String>> = arrayListOf()

I/System.out: [Pair{256 yeet}, Pair{128 yeah_boy}, Pair{64 spaghet}, Pair{32 screaming_kid}, Pair{16 nice}, Pair{8 leeroy}, Pair{4 wow}, Pair{2 damn_son}, Pair{1 baby_a_triple}]

I want to retrieve the String value from a single pair, given the key (Long), i.e. 1 or 32. How can I do that?

I'm populating the list like this:

var index = 0
var uniqueID = 1L
for (item in rawItems) {
    mItemArray.add(index, Pair(uniqueID, item.name))
    println(item.name)
    index += index
    uniqueID += uniqueID
}

Solution

  • You can use find():

    mItemArray.find { it.first == id }?.second