如何将字符串的某些字符与Kotlin中的HashMap 的值交换?

假设我有一个

val s: String = "14ABC5" 

并有一个HashMap

 val b: HashMap = hashMapOf("A" to "10", "B" to "11", "C" to "12", "D" to "13", "E" to "14", "F" to "15" ) 

我将如何在保持顺序(“1”,“4”,“10”,“11”,“12”,“5”)的同时,将10,11,12中的所有A,B,

到目前为止,我有这个

 val result: List = s.toUpperCase().toCharArray().map{ it.toString() }.map{ it -> b.getValue(it)} 

如果String所有字符都存在于HashMap但是我的String也可能包含不存在的键,这将起作用。

您可以使用getOrDefault(...)或Kotlinesque b[it] ?: it ?: b[it] ?: it


顺便说一句,如果你使用隐含的lambda参数名( it ),你可以去掉it ->

您可以使用String作为默认的迭代,并简化您的代码,如下所示:

 s.map { it.toString() } .map { b[it] ?: it }