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

自古美人都是妖i 提交于 2019-12-20 02:34:36

问题


E.g. for List(1, 1, 1, 2, 3, 3, 4) it would be Set(1, 3), because 1 and 3 are the only elements which occur multiple times.


回答1:


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



回答2:


A bit more convoluted but you can avoid having to call toSet.toList, first group the integers:

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

Then collect only the one were the list has length greater as 1:

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

If you want a Set just call toSet.



来源:https://stackoverflow.com/questions/25342596/how-to-get-a-set-of-all-elements-that-occur-multiple-times-in-a-list-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!