Scala best way of turning a Collection into a Map-by-key?

oxbow_lakes picture oxbow_lakes · Mar 23, 2009 · Viewed 147.5k times · Source

If I have a collection c of type T and there is a property p on T (of type P, say), what is the best way to do a map-by-extracting-key?

val c: Collection[T]
val m: Map[P, T]

One way is the following:

m = new HashMap[P, T]
c foreach { t => m add (t.getP, t) }

But now I need a mutable map. Is there a better way of doing this so that it's in 1 line and I end up with an immutable Map? (Obviously I could turn the above into a simple library utility, as I would in Java, but I suspect that in Scala there is no need)

Answer

Ben Lings picture Ben Lings · Jul 14, 2010

You can use

c map (t => t.getP -> t) toMap

but be aware that this needs 2 traversals.