Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a Map in Kotlin?

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)?

like image 225
Grzegorz Piwowarek Avatar asked Jul 28 '17 18:07

Grzegorz Piwowarek


People also ask

What does .map do in Kotlin?

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.

How do I map a list to another list in Kotlin?

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.

What is flatMap 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.


1 Answers

Since the Map consists of Entrys 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 Pairs.

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. 
like image 107
holi-java Avatar answered Sep 22 '22 09:09

holi-java