Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading