在Scala中,它只是map功能.例如,如果hashMap是字符串的hashMap,那么您可以执行以下操作:
val result : HashMap[String,String] = hashMap.map(case(k,v) => (k -> v.toUpperCase))
Run Code Online (Sandbox Code Playgroud)
但是,在Kotlin中,map将地图转换为列表.在Kotlin有同样的方式做同样的事情吗?
Jam*_*ett 54
我不认为一个人的意见是惯用的,但我可能会使用
// transform keys only (use same values)
hashMap.mapKeys { it.key.toUpperCase() }
// transform values only (use same key) - what you're after!
hashMap.mapValues { it.value.toUpperCase() }
// transform keys + values
hashMap.entries.associate { it.key.toUpperCase() to it.value.toUpperCase() }
Run Code Online (Sandbox Code Playgroud)
emu*_*emu 13
该toMap功能似乎是为此而设计的:
hashMap.map { (key, value) ->
key.toLowerCase() to value.toUpperCase()
}.toMap()
Run Code Online (Sandbox Code Playgroud)
它转换Iterable<Pair<K, V>>为Map<K, V>
您可以使用其他人建议的stdlibmapValues函数:
hashMap.mapValues { it.value.uppercase() }
Run Code Online (Sandbox Code Playgroud)
或解构
hashMap.mapValues { (_, value) -> value.uppercase() }
Run Code Online (Sandbox Code Playgroud)
我相信这是最惯用的方式。
| 归档时间: |
|
| 查看次数: |
10352 次 |
| 最近记录: |