关于多个字段的不同问题的 Kotlin 问题

huangapple go评论57阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2023年3月9日 17:30:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定