Home > OS >  Kotlin, is it possible to access the pair of a map?
Kotlin, is it possible to access the pair of a map?

Time:10-16

Is it possible to access the whole Pair of a map, not only the key or a value? Let's say we have a map

map = mapOf(Pair("Example1", 1), Pair("Example2", 2), Pair("Example3", 3))

I would like to access the second pair and put it into a variable, something like I would do with a list:

val ex2 = map[1] #this would result with {"Example2", 2}

And then i would be able to access the pair's key/value like:

ex2.key / ex2.value

More specifically, I would like to use this in my function to return a specific pair of the map.

CodePudding user response:

Not sure if this would help

val mapString = mutableMapOf(1 to "Person", 2 to "Animal")
val (id, creature) = 1 to mapString.getValue(1)


Log.e("MapPair", "$id, $creature")

prints

1, Person

or if you're iterating through the entire map

mapString.forEach {
        val (id, creature) = it.key to it.value
        Log.e("MapPair", "$id : $creature")
}

prints

1 : Person
2 : Animal

or using Pair

val key = 1
val pair = Pair(key, mapString.getValue(key))
Log.e("MapPair", "$pair")

prints

(1, Person)

or if you're iterating through the entire map using Pair

mapString.forEach {
        val pair = Pair(it.key, it.value)
        Log.e("MapPair", "$pair")
}

prints

(1, Person)
(2, Animal)

Update: For iterating through the map you can also go with Destructuring Declarations

val mapString = mutableMapOf(1 to "Person", 2 to "Animal")

for ((key, value) in mapString) {
      Log.e("MapComponents", "$key, $value")
}

CodePudding user response:

From your comment, it seems like you want to fetch the key corresponding to a given value.

val map = mapOf("Chicken" to 20, "Egg" to 10, "Bread" to 5)
val valueToFind = 20
val key = map.toList().find { it.second == valueToFind }?.first
println(key)

Output:

Chicken

If the value doesn't exist, it will give null.

  • Related