How to reverse a Map in Kotlin?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)