[英]How do I swap some characters of a String with values of a HashMap<String,String> in Kotlin?
Assuming I have a 假设我有一个
val s: String = "14ABC5"
and have a HashMap
并有一个
HashMap
val b: HashMap<String,String> = hashMapOf("A" to "10", "B" to "11", "C" to "12", "D" to "13", "E" to "14", "F" to "15" )
How would I change all occurrences of A,B,C with 10, 11, 12 while keeping their order ("1", "4", "10", "11", "12", "5")? 在保持顺序(“ 1”,“ 4”,“ 10”,“ 11”,“ 12”,“ 5”)的同时,我如何用10、11、12更改所有出现的A,B,C?
So far I have this 到目前为止,我有这个
val result: List<String> = s.toUpperCase().toCharArray().map{ it.toString() }.map{ it -> b.getValue(it)}
which works if ALL characters of the String
exist in the HashMap
but my String
may contain inexistent keys as well. 如果
HashMap
存在String
所有字符,但我的String
可能还包含不存在的键,则可以使用。
You could either use getOrDefault(...)
, or the Kotlinesque b[it] ?: it
. 您可以使用
getOrDefault(...)
或Kotlinesque b[it] ?: it
?: b[it] ?: it
。
By the way, if you're using the implicit lambda argument name ( it
), you can get rid of the it ->
. 顺便说一句,如果您使用隐式lambda参数名称(
it
),则可以摆脱it ->
。
You can use the String
as an iterable by default and simplify your code as follows: 您可以默认使用
String
作为可迭代对象,并按如下所示简化代码:
s.map { it.toString() }
.map { b[it] ?: it }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.