我有一个字段列表变量。
val fieldList: List<MutableMap<String, String>>
// fieldList Data :
[ {
"field_id" : "1",
"section_id" : "1",
"section_name" : "section1",
"field_name" : "something_1"
}, {
"field_id" : "2",
"section_id" : "1",
"section_name" : "section1",
"field_name" : "something_2"
}, {
"field_id" : "3",
"section_id" : "2",
"section_name" : "section2",
"field_name" : "something_3"
}, {
"field_id" : "4",
"section_id" : "3",
"section_name" : "section3",
"field_name" : "something_4"
} ]
我想按section_id分组。
结果应如下所示:
val result: List<MutableMap<String, Any>>
// result Data :
[
{
"section_id": "1",
"section_name": "section1",
"field": [
{
"id": “1”,
"name": "something_1"
},
{
"id": “2”,
"name": "something_2"
}
]
},
{
"section_id": "2",
"section_name": "section2",
"field": [
{
"id": “3”,
"name": "something_3"
}
]
},
.
.
.
]
在 Kotlin 中执行此操作的最惯用方法是什么?
我在 Java 中有一个看起来很丑陋的工作版本,但我很确定 Kotlin 有一个很好的方法。
只是到目前为止我还没有找到它!
知道吗?
谢谢
另一种方式:
val newList = originalList.groupBy { it["section_id"] }.values
.map {
mapOf(
"section_id" to it[0]["section_id"]!!,
"section_name" to it[0]["section_name"]!!,
"field" to it.map { mapOf("id" to it["field_id"], "name" to it["field_name"]) }
)
}
操场
此外,正如 broot 所提到的,更喜欢使用数据类而不是这样的映射。
假设我们保证数据是正确的,我们不必验证它,所以:
- 所有字段始终存在,
- 对于特定
section_id
,section_name
始终相同。
这是您可以执行此操作的方法:
val result = fieldList.groupBy(
keySelector = { it["section_id"]!! to it["section_name"]!! },
valueTransform = {
mutableMapOf(
"id" to it["field_id"]!!,
"name" to it["field_name"]!!,
)
}
).map { (section, fields) ->
mutableMapOf(
"section_id" to section.first,
"section_name" to section.second,
"field" to fields
)
}
但是,我建议不要使用地图和列表,而是使用适当的数据类。使用Map
存储已知属性并使用Any
存储String
或List
使用起来非常不方便且容易出错。