kotlin 转换&lt;string,List< string>&gt;Map以将值更改为键

5t7ly7z5  于 2023-11-21  发布在  Kotlin
关注(0)|答案(2)|浏览(182)

我有一个下面的Map,其中包含篮子号码,以名单的水果在篮子里。

val basketMap = mapOf("basket1" to listOf("apples", "oranges", "grapes"),
                      "basket2" to listOf("oranges", "kiwi", "pineapple"),
                      "basket3" to listOf("grapes", "apples", "strawberry"))

字符串
我想将此Map转换为水果篮子列表水果是目前在Ex:

val finalExpectedResult = mapOf("apples" to listOf("basket1", "basket3"),
                                "oranges" to listOf("basket1", "basket2"),
                                "grapes" to listOf("basket1", "basket3"),
                                "kiwi" to listOf("basket2"),
                                "pineapple" to listOf("basket2")
                                "strawberry" to listOf("basket3"))


如何在Kotlin中从上述basketMap实现finalExpectedResultMap

jyztefdp

jyztefdp1#

首先,将map扁平化为一个对(basket, fruit)的列表,然后再次分组:

basketMap.flatMap { (k, v) -> v.map { k to it } }
    .groupBy({ it.second }, { it.first })

字符串
如果我们的集合很大,我们可以使用序列来代替:

basketMap.asSequence()
    .flatMap { (k, v) -> v.asSequence().map { k to it } }
    .groupBy({ it.second }, { it.first })


通过这种方式,我们避免了创建一个巨大的项目列表,而是在迭代源Map的同时构建一个Map。

u5rb5r59

u5rb5r592#

val finalExpectedResult = mutableMapOf<String, MutableList<String>>()

basketMap.forEach { (basket, fruits) -> 
    fruits.forEach { fruit -> //forEach fruit in all the entries
        if (finalExpectedResult[fruit] == null) { //Checks if it's not present as a key in the new map
            finalExpectedResult[fruit] = mutableListOf(basket) //If it's not present, it gets added as a key
        } else {
            finalExpectedResult[fruit]?.add(basket) //Otherwise the basket is added to the list of values of that key
        }
    }
}

字符串
这应该可以了!
如果不存在,它将水果作为键添加,否则,它将包含它的篮子添加到值列表中。
如果你需要map是不可变的,只需调用finalExpectedResult.toMap()并相应地分配它。

相关问题