I need to deduplicate a list of data classes by a ...
# stdlib
m
I need to deduplicate a list of data classes by a particular property of the data class. I have this, but it feels like a roundabout way of doing it:
Copy code
list.groupBy { it.property }.map { (_, list) -> list.first() }
Is there a simpler way? This is something I would normally solve with
.toSet()
, except I only want to consider one property of the data class, not the entire item.
m
I think you're searching for this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct-by.html
Copy code
list.distinctBy { it.property }
e
which is equivalent to
Copy code
list.filter(mutableSetOf<Any?>()::add)
but it's nice to have it as its own function :)
😱 1
m
distinctBy
is exactly what I was hoping for thanks!