英文:
Convert map to the string array with separator
问题
["A=1", "B.C=2"]
英文:
How to convert such map:
val map = mapOf(
"A" to "1",
"B" to mapOf(
"C" to "2"
)
)
to the string array:
["A=1", "B.C=2"]
答案1
得分: 1
我会从这里开始:
fun print(map: Map<*, *>): List<String> = map.map { (key, value) -> when (value) {
is Map<*, *> -> "$key.${print(value).single()}"
else -> "$key=$value"
} }
你还没有说明如果子映射包含多个条目时该怎么办,但你可以根据需要调整这段代码。
英文:
I'd start with this:
fun print(map: Map<*, *>): List<String> = map.map { (key, value) -> when (value) {
is Map<*,*> -> "$key.${print(value).single()}"
else -> "$key=$value"
} }
You haven't said what to do if the sub-map contains anything other than one entry, but you can adjust this code as needed.
答案2
得分: 0
我的解决方案是:
fun toStringList(map: Map<*, *>): List<String> {
val result = ArrayList<String>()
fun processSubmap(submap: Map<*, *>, prefix: String = "") {
submap.apply{} .forEach { (k,v) ->
if(v is Map<*,*>) {
processSubmap(
v,
if(prefix.isEmpty()) k.toString() else "$prefix.$k"
)
} else {
val left = if(prefix.isEmpty()) k.toString() else "$prefix.$k"
result.add("$left=$v")
}
}
}
processSubmap(map)
return result
}
这是您提供的代码的翻译部分。
英文:
My solution is:
fun toStringList(map: Map<*, *>): List<String> {
val result = ArrayList<String>()
fun processSubmap(submap: Map<*, *>, prefix: String = "") {
submap.apply{} .forEach { (k,v) ->
if(v is Map<*,*>) {
processSubmap(
v,
if(prefix.isEmpty()) k.toString() else "$prefix.$k"
)
} else {
val left = if(prefix.isEmpty()) k.toString() else "$prefix.$k"
result.add("$left=$v")
}
}
}
processSubmap(map)
return result
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论