Scala:在Seq of Seqs中查找唯一的Seqs

时间:2018-08-09 22:57:03

标签: scala collections

我什至很难说出我想问的话,所以让我举个例子。

我有一个Seq,其中Occurrence是一个案例类:

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

我正试图凝结为这样:

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

是否有允许我执行此操作的collections API?我想对Seq中的项目进行排序

1 个答案:

答案 0 :(得分:4)

  • 您对列表中的元素进行排序
  • 并将列表转换为Set,因为它只包含不同的元素。

示例

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)))
  • 您还可以distinct代替.toSet.toSeq

示例

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)))

与问题相关的问题-How in Scala to find unique items in List