简体   繁体   中英

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), ie 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
}

您可以使用find()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM