title: Generating a frequency map for a string in Scala
body: <p>Let's say I have a string, "hello", and I want to generate a character frequency map:</p>
  
  <pre><code>Map[Char,Int] = Map(h -&gt; 1, e -&gt; 1, o -&gt; 1, l -&gt; 2)
  </code></pre>
  
  <p>I could do this iteratively:</p>
  
  <pre><code>val str = "hello"
  var counts = new scala.collection.mutable.HashMap[Char,Int]
  for (i &lt;- str) {
      if (counts.contains(i))
          counts.put(i, counts(i) + 1)
      else
          counts.put(i, 1)
  }
  </code></pre>
  
  <p>By messing around in the REPL, I've found I can do something a bit more concise and not using a mutable collection:</p>
  
  <pre><code>&gt; str.groupBy(_.toChar).map{ p =&gt; (p._1, p._2.length)}
  scala.collection.immutable.Map[Char,Int] = Map(h -&gt; 1, e -&gt; 1, o -&gt; 1, l -&gt; 2)
  </code></pre>
  
  <p>But I don't know about the performance characteristics of groupBy() nor what is going on in the block passed to map (like what, exactly, p is).</p>
  
  <p>How do I do this idiomatically using the functional paradigms in Scala?</p>
  
  <hr>
  
  <p>For background, I'm just coming to Scala for the first time from Ruby. In Ruby, I would use <code>inject</code> but I'm not sure what the parallel way to do it in Scala is:</p>
  
  <pre><code>counts = str.each_byte.inject(Hash.new(0)){ |h, c| h[c] += 1; h}
  </code></pre>