Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 253
corazza Avatar asked Jan 31 '26 08:01

corazza


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)
like image 141
corazza Avatar answered Feb 02 '26 00:02

corazza


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.

like image 33
Ende Neu Avatar answered Feb 02 '26 02:02

Ende Neu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!