英文:
kotlin question about distinct by multiple fileds
问题
以下是原始列表:
PersonList: List<Person> = {
  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")
}
结果:按国家和性别去重
结果 ->
listOf(
  {country:"US", gender:"male"}, 
  {country:"CA", gender:"female"}, 
  {country:"CA", gender="male"}
)
如何实现这个?
英文:
Here is original list:
PersonList: List<Person> = {
  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")
}
Result: distinct by country & gender
result ->
listOf(
  {country:"US", gender:"male"}, 
  {country:"CA", gender:"female"}, 
  {country:"CA", gender:"male"}
)
How can I do this?
答案1
得分: 1
以下是您要翻译的代码部分:
fun main() {
    val persons = listOf(
        Person(1, "US", "male"),
        Person(2, "US", "male"),
        Person(3, "CA", "female"),
        Person(4, "CA", "male")
    )
    
    val result =
        persons.distinctBy { it.country to it.gender }.map { mapOf("country" to it.country, "gender" to it.gender) }
    println(result)
    //[{country=US, gender=male}, {country=CA, gender=female}, {country=CA, gender=male}]
}
data class Person(val id: Int, val country: String, val gender: String)
请注意,我已将 HTML 实体编码解码为原始文本。
英文:
Here's an example of how you could do it:
fun main() {
    val persons = listOf(
        Person(1, "US", "male"),
        Person(2, "US", "male"),
        Person(3, "CA", "female"),
        Person(4, "CA", "male")
    )
    
    val result =
        persons.distinctBy { it.country to it.gender }.map { mapOf("country" to it.country, "gender" to it.gender) }
    println(result)
    //[{country=US, gender=male}, {country=CA, gender=female}, {country=CA, gender=male}]
}
data class Person(val id: Int, val country: String, val gender: String)
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论