0

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"),
]

2 Answers 2

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

1

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.