简体   繁体   English

转换不可变 kolin 的更好方法 Map<k,v></k,v>

[英]Better way to transform immutable kolin Map<K,V>

I have a nested immutable kotlin Map<K, Map<K,V>> which I would like to loop through each entry and perform some transformation and produce a new Map<K, Map<K,V>> which transformed key, values.我有一个嵌套的不可变 kotlin Map<K, Map<K,V>> 我想遍历每个条目并执行一些转换并生成一个新的 Map<K, Map<K,V>> 转换键,值.

Here is my current solution but I feel like there would be a better way to achieve this.这是我目前的解决方案,但我觉得会有更好的方法来实现这一目标。

fun main() {
    // I would like to loop through each key,value pair and transform them and produce a new map with transformed values.
    val mapToTransform = mapOf(1 to mapOf("one" to "I"), 2 to mapOf("two" to "II"))
    
    // Here is my current solution to achieve it. Is there any better way to do this?
    val transformedMap = mapToTransform.map { (outerMapKey, innerMap) -> 
        outerMapKey+1 to innerMap.map { (innerMapKey, innerMapValue) ->
            innerMapKey.uppercase() to "$innerMapValue is Roman letter"
        }.toMap()
    }.toMap()
    
    println(transformedMap)
}

First, I should say that I think your current code is perfectly fine and readable.首先,我应该说我认为您当前的代码非常好且可读。 I would not change it.我不会改变它。 However, since you don't seem to like using toMap or creating pairs,但是,由于您似乎不喜欢使用toMap或创建对,

I feel instead of creating pairs and using.toMap() twice there should be a cleaner way.我觉得应该有一种更简洁的方法,而不是创建对并使用 .toMap() 两次。

It is possible to not use toMap or create pairs by repeatedly mapKeys and mapValues :可以不使用toMap或通过重复mapKeysmapValues创建对:

val transformed = mapToTransform
    .mapKeys { (outerMapKey, _) -> outerMapKey + 1}
    .mapValues { (_, innerMap) ->
        innerMap
            .mapKeys { (innerKey, _) -> innerKey.uppercase() }
            .mapValues { (_, innerValue) -> "$innerValue is Roman letter" }
    }

This might be a little more readable depending on who you ask.根据您询问对象,这可能更具可读性。 On the other hand, it creates a lot of intermediate Map s.另一方面,它创建了很多中间Map s。 I'm not sure about how the performance of this compares to your original code, but it probably depends on the contents of the map itself.我不确定它的性能与您的原始代码相比如何,但这可能取决于 map 本身的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM