0

Its hard for me to even put into words what I mean to ask, so let me give an example.

I have a Seq like so, where Occurrence is a case class:

Seq(
  Seq(Occurrence1, Occurrence2, Occurrence3), 
  Seq(Occurrence2, Occurrence3, Occurrence1),
  Seq(Occurrence4),
  Seq(Occurrence5, Occurrence6),
  Seq(Occurrence6, Occurrence5)
)

Which I am trying to condense to look like:

Seq(
  Seq(Occurrence1, Occurrence2, Occurrence3),
  Seq(Occurence4),
  Seq(Occurrence5, Occurrence6)
)

Is there a collections API that allows me to do this? I'd like to sort the items within that Seq

Andrew Allison
  • 1,122
  • 2
  • 13
  • 30
  • 1
    Possible duplicate of [How in Scala to find unique items in List](https://stackoverflow.com/questions/1538598/how-in-scala-to-find-unique-items-in-list) – James Whiteley Aug 10 '18 at 08:36
  • Scala 2.13 adds `distinctBy`, which is very useful here. 2.12 and earlier don't have it. – Seth Tisue Aug 10 '18 at 18:34
  • Someone has been systematically going through my profile and downvoting all questions and answers I've provided on Stackoverflow. The admins seem to be content letting it happen as well. Therefore, I would ask that any subsequent visitors of this post please vote genuinely and leave a comment explaining why you did or did not find the post useful. I'm not trying to indulge in some pathetic tit-for-tat, I just want to help the next person. Thank you! – Andrew Allison Oct 16 '18 at 14:55

1 Answers1

4
  • You sort the elements in list
  • and convert the list to Set as set contains only the distinct elements.

Example,

final case class Occurance(times: Int)

val Occurrence1 = Occurance(times = 1)
val Occurrence2 = Occurance(times = 2)
val Occurrence3 = Occurance(times = 3)
val Occurrence4 = Occurance(times = 4)
val Occurrence5 = Occurance(times = 5)
val Occurrence6 = Occurance(times = 6)

val data = Seq(
        Seq(Occurrence1, Occurrence2, Occurrence3), 
        Seq(Occurrence2, Occurrence3, Occurrence1),
        Seq(Occurrence4),
        Seq(Occurrence5, Occurrence6),
        Seq(Occurrence6, Occurrence5)
      )

data.map(_.sortBy {_.times}).toSet.toSeq

//res0: Seq[Seq[Occurance]] = Vector(List(Occurance(1), Occurance(2), Occurance(3)), List(Occurance(4)), List(Occurance(5), Occurance(6)))
  • you can also distinct instead of .toSet.toSeq,

Example,

data.map(_.sortBy{_.times}).distinct
//res1: Seq[Seq[Occurance]] = List(List(Occurance(1), Occurance(2), Occurance(3)), List(Occurance(4)), List(Occurance(5), Occurance(6)))

Somehow related question - How in Scala to find unique items in List

prayagupa
  • 30,204
  • 14
  • 155
  • 192