将地图转换为带分隔符的字符串数组

huangapple go评论56阅读模式
英文:

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&lt;*, *&gt;): List&lt;String&gt; = map.map { (key, value) -&gt; when (value) {
        is Map&lt;*,*&gt; -&gt; &quot;$key.${print(value).single()}&quot;
        else -&gt;  &quot;$key=$value&quot;
    } }

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&lt;*, *&gt;): List&lt;String&gt; {
    val result = ArrayList&lt;String&gt;()

    fun processSubmap(submap: Map&lt;*, *&gt;, prefix: String = &quot;&quot;) {
        submap.apply{} .forEach { (k,v) -&gt;
            if(v is Map&lt;*,*&gt;) {
                processSubmap(
                    v,
                    if(prefix.isEmpty()) k.toString() else &quot;$prefix.$k&quot;
                )
            } else {
                val left = if(prefix.isEmpty()) k.toString() else &quot;$prefix.$k&quot;
                result.add(&quot;$left=$v&quot;)
            }
        }
    }

    processSubmap(map)
    return result
}

huangapple
  • 本文由 发表于 2023年6月19日 21:41:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定