kotlin 基于项目将Map〈String,List>拆分< Item>为两个键重叠的分离Map

ar7v8xwq  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(95)

我正在尝试找出如何有效地将一个Map拆分为两个Map。原始Map看起来如下所示,但要大得多:

val sourceMap = <Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = true), Item(owned: Boolean = false)),
   "key2", listOf(Item(owned: Boolean = false), Item(owned: Boolean = false)),
   "key3", listOf(Item(owned: Boolean = true), Item(owned: Boolean = true))
)

我想把这个Map分成两个Map,在一个Map中把键和所有“owned = true”项关联起来,在另一个Map中把键和“owned = false”项关联起来。

val ownedMap = Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = true)),
   "key3", listOf(Item(owned: Boolean = true), Item(owned: Boolean = true))
)

val unOwnedMap = Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = false)),
   "key2", listOf(Item(owned: Boolean = false), Item(owned: Boolean = false)),
)

编辑:理想情况下,答案将允许所有排序在原始sourceMap的一次传递中发生。

sg3maiej

sg3maiej1#

以下代码可能会有所帮助:

val ownedMap = mutableMapOf<String, MutableList<Item>>()
val unOwnedMap = mutableMapOf<String, MutableList<Item>>()

sourceMap.forEach { (key, list) ->
    list.forEach { item ->
        if (item.owned) {
            ownedMap.addToListInMap(key, item)
        } else {
            unOwnedMap.addToListInMap(key, item)
        }
    }
}

fun <K, V> MutableMap<K, MutableList<V>>.addToListInMap(key: K, value: V) {
    if (this[key] != null) {
        this[key]?.add(value)
    } else {
        this[key] = mutableListOf(value)
    }
}

你也可以不使用扩展函数来编写代码,这样看起来就像这样:

val ownedMap = mutableMapOf<String, MutableList<Item>>()
val unOwnedMap = mutableMapOf<String, MutableList<Item>>()

sourceMap.forEach { (key, list) ->
    list.forEach { item ->
        if (item.owned) {
            if (ownedMap[key] != null) {
                ownedMap[key]?.add(item)
            } else {
                ownedMap[key] = mutableListOf(item)
            }
        } else {
            if (unOwnedMap[key] != null) {
                unOwnedMap[key]?.add(item)
            } else {
                unOwnedMap[key] = mutableListOf(item)
            }
        }
    }
}

相关问题