Doo9104
Doo9104

Reputation: 53

kotlin how to remove duplicate through some value in object array?

how to remove duplicate through some value in object array?


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)

Person 3 and person 7 have a "female" gender and have the same name. So person7 needs to be removed.

But "male" gender can have duplicated name.

And the order of the list must be maintained.

expect result

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

Upvotes: 0

Views: 125

Answers (2)

Ivo
Ivo

Reputation: 23154

I believe this does what you want:

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

Upvotes: 1

Allesio Pellicciotta
Allesio Pellicciotta

Reputation: 61

You could do something like this, assuming the order is indicated by the id field of the Person class:

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 }

Upvotes: 1

Related Questions