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

如何在Kotlin中创建按Country分组的MutableMap<String, List<Person>>

问题描述

现有一个Person对象列表:

Person(id=1, country="US")
Person(id=2, country="US")
Person(id=3, country="CA")

需要将其按country字段分组,存入一个MutableMap<String, List<Person>>,期望结果为:

group: Map<String, List> = {"US"=listOf(Person(id=1, country="US"), Person(id=2, country="US")), "CA"=listOf(Person(id=3, country="CA"))}

初始定义的Map为:

val group: MutableMap<String, List<Person>> = mutableMapOf()
实现方案

Kotlin标准库提供了简洁的分组能力,以下是两种常用实现方式:

方式一:使用groupBy函数(推荐)

groupBy是Kotlin集合的扩展函数,会直接返回按指定键分组后的Map,如果需要可变Map,可调用toMutableMap()转换:

// 先定义原始Person列表
val personList = listOf(
    Person(1, "US"),
    Person(2, "US"),
    Person(3, "CA")
)

// 直接得到不可分组Map
val immutableGroup = personList.groupBy { it.country }

// 转换为可变Map,匹配初始定义的类型
val group: MutableMap<String, List<Person>> = personList.groupBy { it.country }.toMutableMap()

方式二:手动遍历填充(自定义逻辑场景)

如果需要更灵活的分组逻辑(比如分组时额外过滤、转换元素),可以手动遍历列表填充Map:

val personList = listOf(
    Person(1, "US"),
    Person(2, "US"),
    Person(3, "CA")
)

val group: MutableMap<String, List<Person>> = mutableMapOf()
personList.forEach { person ->
    // 获取当前国家对应的列表,不存在则创建空列表
    val currentList = group.getOrDefault(person.country, emptyList()).toMutableList()
    currentList.add(person)
    group[person.country] = currentList
}

扩展说明

如果分组后需要对每个组的列表做额外处理,比如排序、过滤,可以结合mapValues使用:

// 分组后将每个组的Person按id升序排序
val sortedGroup = personList.groupBy { it.country }
    .mapValues { (_, personList) -> personList.sortedBy { it.id } }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:14