I am trying to reverse 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 any better way of doing this without using a middleman(middlelist)?
I am trying to reverse 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 any better way of doing this without using a middleman(middlelist)?
由于Map
由Entry
组成,而不是Iterable
,您可以改用Map#entries.它将映射到Map#entrySet以创建Set<Entry>
的后视图,例如:
val reversed = map.entries.associateBy({ it.value }) { it.key }
OR使用Iterable#associate,这将创建额外的Pair
.
val reversed = map.entries.associate{(k,v)-> v to k}
OR使用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.