oxbow_lakes oxbow_lakes - 10 months ago 59
Scala Question

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

If I have a collection

of type
and there is a property
(of type
, 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 Source

You can use

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

but be aware that this needs 2 traversals. To get away with one use

c.map(t => t.getP -> t)(collection.breakOut).toMap: Map[P, T]

breakOut instructs .map to immediately create a collection of the expected type.