以函数/ Scala方式查找每个元素出现次数的最佳方法是什么?
Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
因此,我需要像
这样的东西Set(("a", 1), ("b", 3), ("c", 2))
谢谢!
答案 0 :(得分:2)
scala> val s = Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
s: Seq[scala.collection.immutable.Set[String]] =
List(Set(a, b, c), Set(b), Set(b, c))
scala> s.flatten
res0: Seq[String] =
List(a, b, c, b, b, c)
scala> s.flatten.groupBy(identity)
res3: scala.collection.immutable.Map[String,Seq[String]] =
Map(b -> List(b, b, b), a -> List(a), c -> List(c, c))
scala> s.flatten.groupBy(identity).map { case (k, v) => (k, v.size) }.toSet
res7: scala.collection.immutable.Set[(String, Int)] =
Set((b,3), (a,1), (c,2))
答案 1 :(得分:-1)
scala> val x = Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
x: Seq[scala.collection.immutable.Set[String]] = List(Set(a, b, c), Set(b), Set(b, c))
scala> (x.flatten groupBy identity mapValues (_.size)).toSet
res3: scala.collection.immutable.Set[(String, Int)] = Set((b,3), (a,1), (c,2))