Reputation: 2583
What is the best way to find a number of occurrences of each element in a functional/Scala way?
Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
As a result, I need something like
Set(("a", 1), ("b", 3), ("c", 2))
Thank you!
Upvotes: 1
Views: 38
Reputation: 1084
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))
Upvotes: -1
Reputation: 7768
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))
Upvotes: 2