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

eg. for List(1, 1, 1, 2, 3, 3, 4)

it will be Set(1, 3)

because 1 and 3 are the only items that happen multiple times.

+3


source to share


2 answers


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

      



+7


source


A little more confusing, but you can avoid the call toSet.toList

by putting in integers first:

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 we collect only one of them: the length of the list is greater than 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 Set

just want to call toSet

.

+5


source







All Articles