Home > Mobile >  Kotlin how convert map with long and Pair to other map?
Kotlin how convert map with long and Pair to other map?

Time:09-15

I have a construct like this:

     var values = mutableMapOf<Long, Pair<String, Boolean>>()

No I need to have one map from this above like this:

     val transformedMap = Map<Long, String>

I cannot transform this first to second. Andy suggestions?

CodePudding user response:

Most of iterators will require a variable for storing the resulting map, but I think associate can do it directly:

values.entries.associate {
    it.key to it.value.first
}

The other options are like this

val output = mutableMapOf<Long, String>()

//values iterator, for, forEach, keys, etc
output[key] = values[key]?.first

CodePudding user response:

You can do

val transformedMap = values.mapValues { it.value.first }
  • Related