Pedro Gonçalves
Pedro Gonçalves

Reputation: 121

Scala number of occurences of element in list of lists

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

Answers (2)

Puneeth Reddy V
Puneeth Reddy V

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

nmat
nmat

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

Related Questions