You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin如何将List<MutableMap<String,String>>按section_id分组为目标结构

Kotlin 惯用实现方案

直接使用Kotlin标准库集合操作符即可实现,代码如下:

val result: List<MutableMap<String, Any>> = fieldList
    // 按section_id完成分组
    .groupBy { it["section_id"] }
    // 每个分组转换为目标结构
    .map { (sectionId, sameSectionFields) ->
        mutableMapOf(
            "section_id" to sectionId.orEmpty(),
            // 同分组下section_name统一,取首个元素值即可
            "section_name" to sameSectionFields.first()["section_name"].orEmpty(),
            "field" to sameSectionFields.map { fieldItem ->
                mutableMapOf(
                    "id" to fieldItem["field_id"].orEmpty(),
                    "name" to fieldItem["field_name"].orEmpty()
                )
            }
        )
    }

补充说明

  • orEmpty()是安全取值写法,如果你能保证数据源中所有key都存在且非空,可以替换为!!
  • 如果你不需要返回结果的可变性,可以把所有mutableMapOf替换为mapOf,性能更优
  • 若业务允许不强制使用Map结构,更推荐定义数据类实现,类型更安全、代码可维护性更高,示例如下:
// 定义数据类
data class Section(
    val section_id: String,
    val section_name: String,
    val field: List<Field>
)
data class Field(val id: String, val name: String)

// 转换代码
val result: List<Section> = fieldList
    .groupBy { it["section_id"] }
    .map { (sectionId, sameSectionFields) ->
        Section(
            section_id = sectionId.orEmpty(),
            section_name = sameSectionFields.first()["section_name"].orEmpty(),
            field = sameSectionFields.map { fieldItem ->
                Field(
                    id = fieldItem["field_id"].orEmpty(),
                    name = fieldItem["field_name"].orEmpty()
                )
            }
        )
    }

内容的提问来源于stack exchange,提问作者nkhcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 15:24:01