How to change a map in Kotlin?
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