Search code examples
scalascala-collections

Find a number of occurrences in internal collections in a functional way


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!


Solution

  • Use flatten and groupBy:

    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))