In Scala, it's just the map
function. For example, if hashMap is a hashMap of strings, then you can do the following:
val result : HashMap[String,String] = hashMap.map(case(k,v) => (k -> v.toUpperCase))
In Kotlin, however, map
turns the map into a list. Is there an idiomatic way of doing the same thing in Kotlin?
When transforming maps, you have two options: transform keys leaving values unchanged and vice versa. To apply a given transformation to keys, use mapKeys() ; in turn, mapValues() transforms values. Both functions use the transformations that take a map entry as an argument, so you can operate both its key and value.
To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.
mapOf — creating an immutable map The first and most standard way of creating a map in Kotlin is by using mapOf . mapOf creates an immutable map of the key-value pairs we provide as parameters. Since the map is immutable, we won't find methods like put , remove or any other modifying functions.
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.
I don't think one person's opinion counts as idiomatic, but I'd probably use
// transform keys only (use same values) hashMap.mapKeys { it.key.uppercase() } // transform values only (use same key) - what you're after! hashMap.mapValues { it.value.uppercase() } // transform keys + values hashMap.entries.associate { it.key.uppercase() to it.value.uppercase() }
Note: or toUpperCase()
prior to Kotlin 1.5.0
The toMap
function seems to be designed for this:
hashMap.map { (key, value) -> key.toLowerCase() to value.toUpperCase() }.toMap()
It converts Iterable<Pair<K, V>>
to Map<K, V>
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