Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to transform map in kotlin?

Tags:

hashmap

kotlin

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?

like image 930
U Avalos Avatar asked Feb 07 '17 04:02

U Avalos


People also ask

How do you change map 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.

How do I change the map value in Kotlin?

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.

How do you make an immutable map on Kotlin?

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.

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.


2 Answers

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

like image 104
James Bassett Avatar answered Sep 24 '22 03:09

James Bassett


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>

like image 27
emu Avatar answered Sep 24 '22 03:09

emu