0

So I have a list such as this:

val list = List(List(1,2,3),List(3,4,8),List(4,2,3))

In the above case, the output I want looks like this:

Map(1 -> 1, 2 -> 1, 3 -> 3, 4 -> 2, 8 -> 1)

If the List was a normal list, I would do:

list.groupBy(identity).mapValues(_.size)

To achieve the expected outcome. So, how do I do this for a 2d list?

Joe Johnes
  • 27
  • 5

1 Answers1

5

Using only scala, you can flatten the first list and then apply the same method

list.flatten.groupBy(identity).mapValues(_.size) // Map(1 -> 1, 2 -> 2, 3 -> 3, 8 -> 1, 4 -> 2)

Or using Cats/Scalaz |+| (combine) operator.

list.map(l => l.groupBy(identity).mapValues(_.size)).reduce(_ |+| _) //  Map(1 -> 1, 2 -> 2, 3 -> 3, 8 -> 1, 4 -> 2)