Scala best way of turning a Collection into a Map-by-key? (2nd variant)

dictionary, list, scala, scala-collections

Solution

With Scala 2.8.0:

list.groupBy(_.length)

It can not get any simpler than that!

Problem

(This is a variant to this Q&A) Say I have this: ``` List( "foo", "bar", "spam" ) ``` I want to create a Map for which the key is the length of the String and the value is a Collection of all the Strings that have that length. In other words, given the about List, we'd get: ``` Map( 3 -> List(foo, bar), 4 -> List(spam) ) ``` The code I've written to do this is: ``` list.foldLeft(Map[Long, List[String]]()) { (m, s) => m(s.length) = s :: ( if ( m.contains(s.length) ) m(s.length) else Nil ) } ``` This works, but it adds a lot of ugliness to the elegant answer Daniel Spiewak provided to the original question (referenced above). Any ideas how to improve the solution for my variant? Thanks! Sean

Original source

Related problems