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)?
Returns a list containing the results of applying the given transform function to each element in the original array. Returns a list containing the results of applying the given transform function to each element in the original collection.
You can use the map() function to easily convert a list of one type to a list of another type. It returns a list containing the results of applying the specified transform function to each element in the original list. That's all about conversion between lists of different types in Kotlin.
In kotlin language, the collections are one of the most important util packages in that some pre-defined classes like map, list etc. The flatMap() is one of the methods that is used to create the single set of list entries from the input results.
Since the Map
consists of Entry
s and it is not Iterable
you can use Map#entries instead. It will be mapped to Map#entrySet to create a backed view of Set<Entry>
, for example:
val reversed = map.entries.associateBy({ it.value }) { it.key }
OR use Iterable#associate, which will create additional Pair
s.
val reversed = map.entries.associate{(k,v)-> v to k}
OR using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With