kotlin 如何通过对象数组中的某个值删除重复项?

b0zn9rqh  于 2022-11-25  发布在  Kotlin
关注(0)|答案(2)|浏览(115)

如何通过对象数组中某个值去重?

data class Person(
    val id: Int,
    val name: String,
    val gender: String
)


val person1 = Person(1, "Lonnie", "female")
val person2 = Person(2, "Noah", "male")
val person3 = Person(3, "Ollie", "female")
val person4 = Person(4, "William", "male")
val person5 = Person(5, "Lucas", "male")
val person6 = Person(6, "Mia", "male")
val person7 = Person(7, "Ollie", "female")

val personList = listOf(person1,person2,person3,person4,person5,person6,person7)

人物3和人物7的性别都是“女性”,名字也一样,所以需要去掉人物7。

但“男性”性别可以有重复的名称。

并且必须保持列表的顺序。
预期结果

[
    Person(1, "Lonnie", "female"),
    Person(2, "Noah", "male"),
    Person(3, "Ollie", "female"),
    Person(4, "William", "male"),
    Person(5, "Lucas", "male"),
    Person(6, "Mia", "male"),
]
fnvucqvd

fnvucqvd1#

假设Person类的id字段指示了顺序,您可以执行类似以下的操作:

val personList = listOf(person1,person2,person3,person4,person5,person6,person7)
    .partition { it.name == "male" }
    .let { (males, females) -> males + females.distinctBy { it.name } }
    .sortedBy { it.id }
o3imoua4

o3imoua42#

我相信这是你想要的:

val result = personList.filter {
  person -> person.gender == "male" || (personList.first {
    person.name == it.name && person.gender == it.gender
  } == person)
}

相关问题