gpt4 book ai didi

kotlin - 合并 map 列表(字符串列表)

转载 作者:行者123 更新时间:2023-12-02 13:36:16 25 4
gpt4 key购买 nike

宝贝Kotlin开发人员在这里:)

考虑以下结构:

[
{ "color": ["red", "blue"] },
{ "color": ["red", "green"] },
{ "shape": ["square", "circle"] },
{ "shape": ["rectangle"] }
]

我想获得键和它们各自的值合并的以下结果:
[
{ "color": ["red", "blue", "green"] },
{ "shape": ["square", "circle", "rectangle"] }
]

经过一番研究,我想到的是这样的东西(无法工作/编译),但是我缺少了一些东西:
val colors1 = mapOf("color" to listOf("red", "blue"))
val colors2 = mapOf("color" to listOf("red", "green"))
val shapes1 = mapOf("color" to listOf("square", "circle"))
val shapes2 = mapOf("color" to listOf("rectangle"))
var mainList = mutableListOf(colors1, colors2, shapes1, shapes2)

mainList.reduce { acc, it -> (acc.asSequence() + it.asSequence())
.distinct()
.groupBy({it.key}, {it.value})
.mapValues { (_, values) -> values.flatten().distinct() }

任何帮助将不胜感激。

最佳答案

可以将reduce与 map flatMap结合使用,而不是将 map 与entries合并。所以它应该这样工作:

mainList
.flatMap { it.entries }
.groupBy({ it.key }, { it.value })
.mapValues { (_, values) -> values.flatten().toSet() }

(runnable sample)

同样,更有效的方法来平整最后一行中的值是:
    .mapValues { (_, values) -> values.flatMapTo(mutableSetOf()) { it } }

这消除了创建用于存储 flatten()distinct() / toSet()之间的值的中间集合的开销,但仍确保了这些项是唯一的,因为它们已添加到 mutableSet()中。

重新分配 mainList的样本: (link)

关于kotlin - 合并 map 列表(字符串列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56397262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com