1

I see that Scala has a distinct method which will take a sequence and return a new sequence without any duplicate elements.

Seq(1,1,2,3,2,5).distinct // returns Seq(1,2,3,5)

I would like to do something similar, but base the uniqueness on the results of a function. Is there a clean idiomatic way to do this in Scala?

As an example in another language, I know Groovy's analogous unique method can take a closure to determine the uniqueness function:

[1,3,4,5].unique { it % 2 } // returns [1,4]

Is there a similarly short and descriptive approach in Scala, or am I best served with something like the following?

Seq(1,3,4,5).groupBy(_ % 2).values.map(_.head)
M. Justin
  • 14,487
  • 7
  • 91
  • 130
  • 1
    Very similar: https://stackoverflow.com/questions/3912753/scala-remove-duplicates-in-list-of-objects – Xavier Guihot Jan 16 '19 at 20:54
  • 1
    @XavierGuihot Good find. I had no luck finding the other question, probably since I was searching for it based on the inverse definition (retaining distinct elements vs. removing duplicate ones) – M. Justin Jan 16 '19 at 20:58
  • I think it's difficult to add anything to the duplicate proposed by XavierGuihot, please leave a comment if you disagree. – Andrey Tyukin Jan 16 '19 at 21:07
  • 1
    @AndreyTyukin Nope, marking as a duplicate seems reasonable. – M. Justin Jan 16 '19 at 21:09

1 Answers1

4

As noted in this answer to a similar question, Scala 2.13 adds a distinctBy method to sequences:

Seq(1,3,4,5).distinctBy(_ % 2)
M. Justin
  • 14,487
  • 7
  • 91
  • 130