fun flipValues(values: Map<String, Double>): Map<Double, String> {
return values.map { it.value to it.key }.toMap()
}
2 Likes
brillant solution! Thanks!
Slick! I was trying to figure out the syntax for this and couldn’t. Nicely done. Mine wound up looking a bit more clunky
fun flipValues(map: Map<String, Double>): Map<Double, String>{
val studentGrades = map.values.toList()
val studentName = map.keys.toList()
return studentGrades.zip(studentName).toMap()
}
Just adding my spin to this solution using extensions and generics.
fun <K, V> Map<K, V>.flipValues(): Map<V, K>{
return this.map {
it.value to it.key
}.toMap()
}
edit: I replied to the wrong post and only now I notice this solution being very similar to mine. Oh well.
I added some generics to my solution:
fun <T1,T2> flipValues(m: Map<T1, T2>) : Map<T2, T1> {
return m.map { (key, value) -> value to key }.toMap()