dictionary - How to reverse a Map in Kotlin? -


i trying reverse map in kotlin. far, have come with:

mapof("foo" 42)   .tolist()   .map { (k, v) -> v k }   .tomap() 

is there better way of doing without using middleman(middlelist)?

since map consist of entrys , not iterable. can use map#entries instead, mapped map#entryset create backed view of set<entry>, example:

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

or use iterable#associate, create additional pairs.

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

or using map#foreach instead. example:

val reversed = mutablemapof<int, string>().also {     //     v-- use `foreach` here          map.foreach { (k, v) -> it.put(v, k) }  }.tomap() // ^--- can add `tomap()` create immutable map. 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -