如何在Kotlin中根据country和gender多字段对列表去重?
Kotlin中根据多字段去重并提取指定字段的实现方法
方法1:自定义数据类作为唯一标识(推荐)
Kotlin的data class会自动生成equals()和hashCode()方法,天然适合作为去重的唯一键。
- 定义包含目标字段的数据类:
data class CountryGender(val country: String, val gender: String)
- 映射原列表并去重:
val personList: List<Person> = listOf( Person(id=1, country="US", gender="male"), Person(id=2, country="US", gender="male"), Person(id=3, country="CA", gender="female"), Person(id=4, country="CA", gender="male") ) val uniquePairs = personList.map { CountryGender(it.country, it.gender) } .distinct()
- 转换为示例中的Map结构:
val result = uniquePairs.map { mapOf("country" to it.country, "gender" to it.gender) }
方法2:使用内置Pair作为临时键
如果不想额外定义类,可直接用Kotlin内置的Pair(本质也是data class):
val uniquePairs = personList.map { Pair(it.country, it.gender) } .distinct() val result = uniquePairs.map { mapOf("country" to it.first, "gender" to it.second) }
方法3:通过分组实现去重
利用groupBy()将同字段组合的元素归为一组,再提取每组的任意元素:
val result = personList.groupBy { Pair(it.country, it.gender) } .values .map { group -> mapOf("country" to group.first().country, "gender" to group.first().gender) }
注意事项
原Person类的equals()通常基于id(若为data class),因此不能直接对Person列表调用distinct(),必须明确指定去重的字段组合。如果不需要Map结构,直接返回CountryGender或Pair集合会更具类型安全性。
内容的提问来源于stack exchange,提问作者rime
相关产品推荐
相关产品推荐

