我什至很难说出我想问的话,所以让我举个例子。
我有一个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中的项目进行排序
答案 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)))