title: Count occurrences of each element in a List[List[T]] in Scala
body: <p>Suppose you have</p>
  
  <pre><code>val docs = List(List("one", "two"), List("two", "three"))
  </code></pre>
  
  <p>where e.g. List("one", "two") represents a document containing terms "one" and "two", and you want to build a map with the document frequency for every term, i.e. in this case</p>
  
  <pre><code>Map("one" -&gt; 1, "two" -&gt; 2, "three" -&gt; 1)
  </code></pre>
  
  <p>How would you do that in Scala? (And in an efficient way, assuming a much larger dataset.)</p>
  
  <p>My first Java-like thought is to use a mutable map:</p>
  
  <pre><code>val freqs = mutable.Map.empty[String,Int]
  for (doc &lt;- docs)
    for (term &lt;- doc)
      freqs(term) = freqs.getOrElse(term, 0) + 1
  </code></pre>
  
  <p>which works well enough but I'm wondering how you could do that in a more "functional" way, without resorting to a mutable map?</p>