Search code examples
scaladictionaryfiltertuplessize

Filter groups by size after using groupby function in Scala


I have a map with some key-value pairs where the keys are tuples and the values are strings.
for example:

Map((1,0) -> "a", (3,1) -> "b", (1,2) -> "c")

After grouping by the first element of the tuple key:

Map((1,0) -> "a", (3,1) -> "b", (1,2) -> "c").groupBy(_._1._1)

I get the following:

(1,Map((1,0) -> a, (1,2) -> c))(3,Map((3,1) -> b))

Now my question is, what would be the proper way to filter a group with a given size? for exmaple, if I want to filter the groups with size 2 I should get the following:

(1,Map((1,0) -> a, (1,2) -> c))

Solution

  • Use .filter(_._2.size == 2):

    scala> Map((1,0) -> "a", (3,1) -> "b", (1,2) -> "c").groupBy(_._1._1).filter(_._2.size == 2)
    res0: Map[Int,Map[(Int, Int),String]] = Map(1 -> Map((1,0) -> a, (1,2) -> c))