...">

How to change a map in Kotlin?

I'm trying to flip a map in Kotlin. So far I have come up with:

mapOf("foo" to 42)
  .toList()
  .map { (k, v) -> v to k }
  .toMap()

Is there a better way to do this without using an intermediary (middle list)?

+6
source share
2 answers

Since it Mapconsists of Entryand is not Iterable. but you can use Map Entries # instead , it will appear on Map # entrySet to create a backup Set<Entry>, for example:

val reversed = map.entries.associateBy({ it.value }) { it.key }

OR use Iterable # associate , but it will create additional Pairs.

val reversed = map.entries.associate{(k,v)-> v to k}

, Map # forEach. :

val reversed = mutableMapOf<Int, String>().also {
    //     v-- use `forEach` here     
    map.forEach { (k, v) -> it.put(v, k) } 
}.toMap()
// ^--- you can add `toMap()` to create an immutable Map.
+10

, - (, , )

fun <K, V> Map<K, V>.reversed() = HashMap<V, K>().also { newMap ->
    entries.forEach { newMap.put(it.value, it.key) }
}

, apply , entries.forEach ( Map::forEach)

0

All Articles