I have a List[A]
, how is a idiomatic way of removing duplicates given an equality function (a:A, b:A) => Boolean
? I cannot generally override equals
for A
The way I can think now is creating a wrapping class AExt
with overridden equals
, then
list.map(new AExt(_)).distinct
But I wonder if there's a cleaner way.
There is a simple (simpler) way to do this:
list.groupBy(_.key).mapValues(_.head)
If you want you can use the resulting map instantly by replacing _.head
by a function block like:
sameElements => { val observedItem = sameElements.head
new A (var1 = observedItem.firstAttr,
var2 = "SomethingElse") }
to return a new A
for each distinct element.
There is only one minor problem. The above code (list.groupBy(_.key).mapValues(_.head)
) didnt explains very well the intention to remove duplicates. For that reason it would be great to have a function like distinctIn[A](attr: A => B)
or distinctBy[A](eq: (A, A) -> Boolean)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With