Hi! I have a list of objects, lets say a list of P...
# getting-started
k
Hi! I have a list of objects, lets say a list of Person. I want to remove all duplicates from that list based on the combination of person.name and person.age. What is the "kotlin" way to do so?
d
list.distinctBy { it.name to it.age }
If you have more than one value to compare:
list.distinctBy { listOf(it.name, it.firstName, it.age) }
k
Thanks!
Shouldn't it find the same amount of duplicates as
.groupingBy { it.name to it.age }.eachCount().filterValues { it > 1 }
?
d
Well, it doesn't really count duplicates. It filters them out
But that should do something similar
k
That's true, then it works 🙂
d
You can also use
Triple
if you have 3 properties to compare
k
Sweet, thanks!