簡體   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