简体   繁体   English

Kotlin:将列表分组到地图中

[英]Kotlin: Group a List into a Map of Maps

How to group list into map of maps using lambdas? 如何使用Lambda将列表分组到地图中? Imperative solution looks following: 命令式解决方案如下所示:

private class Data(val a: Int, val b: Int, val c: Int)

@JvmStatic
fun main(args: Array<String>) {
    val dataList = listOf(Data(1, 2, 3), Data(4, 5, 6), Data(7, 8, 9), Data(1, 10, 11))
    val result = mutableMapOf<Int, MutableMap<Int, Int>>()
    for (data in dataList) {
        val aMap = result.getOrPut(data.a) { mutableMapOf() }
        aMap[data.b] = data.c
    }
    println(result)
}

You can do this: 你可以这样做:

dataList.groupBy { it.a }
        .mapValues { (_, v) -> v.associate { it.b to it.c } }

The groupBy function creates a Map<Int, List<Data>> , where the List<Data> is all data-objects that shares the same value in a . groupBy函数创建一个Map<Int, List<Data>> ,其中所述List<Data>是所有数据对象,在共享相同的值a Then I map the values of the Map , creating the structure you needed. 然后,我映射的数值Map ,你创造必要的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM