繁体   English   中英

如何获取Scala中列表中多次出现的所有元素集?

[英]How to get a set of all elements that occur multiple times in a list in Scala?

例如,对于List(1, 1, 1, 2, 3, 3, 4) 1,1,1,2,3,3,4 List(1, 1, 1, 2, 3, 3, 4) ,它将是Set(1, 3) ,因为1和3是多次出现的唯一元素。

val s = List(1, 1, 1, 2, 3, 3, 4) // a list with non-unique elements
(s diff s.distinct) toSet // Set(1, 3)

有点复杂但你可以避免必须调用toSet.toList ,首先对整数进行分组:

scala> s.groupBy(identity)
res13: scala.collection.immutable.Map[Int,List[Int]] = 
  Map(2 -> List(2), 4 -> List(4), 1 -> List(1, 1, 1), 3 -> List(3, 3))

然后只收集列表长度大于1的那个:

scala> s.groupBy(identity).collect { case (v, l) if l.length > 1 => v }
res17: scala.collection.immutable.Iterable[Int] = List(1, 3)

如果你想要Set只调用toSet

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM