Reputation: 121
To make it simple, let's imagine I have the following input:
List(List("A", "A"), List("A", "B"), List("B", "C"), List("B", "C"))
How would it be possible to group the elements inside the lists in such fashion so that I would know how many lists are they in. For example, following the output of a mapValues function just to illustrate what I mean, the result of the previous input should be something like:
Map("A" -> 2, "B" -> 3, "C" -> 2)
Just to be sure I made clear what I mean, a way to interpret the result would be to say that "A" is present in 2 of the sub-lists (regardless of how many times it appears inside of a particular sub-list), "B" is present in 3 of the sub-lists and "C" is in 2. I just want a way to map how many different sub-lists each of the individual elements are present in.
Upvotes: 0
Views: 902
Reputation: 1568
You can also use fold
operation to like this
list.flatten.foldLeft(Map.empty[String, Int])((map, word) => map + (word -> (map.getOrElse(word,0) + 1)))
//scala> res2: scala.collection.immutable.Map[String,Int] = Map(A -> 3, B -> 3, C -> 2)
Upvotes: 0
Reputation: 7591
Disregarding performance, this would work:
val list = List(List("A", "A"), List("A", "B"), List("B", "C"), List("B", "C"))
val elements = list.flatten.distinct
elements.map(el => el -> list.count(_.contains(el))).toMap
Upvotes: 2