How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map?

Jesper picture Jesper · May 27, 2010 · Viewed 43.9k times · Source

I have a Seq containing objects of a class that looks like this:

class A (val key: Int, ...)

Now I want to convert this Seq to a Map, using the key value of each object as the key, and the object itself as the value. So:

val seq: Seq[A] = ...
val map: Map[Int, A] = ... // How to convert seq to map?

How can I does this efficiently and in an elegant way in Scala 2.8?

Answer

Seth Tisue picture Seth Tisue · May 28, 2010

Since 2.8 Scala has had .toMap, so:

val map = seq.map(a => a.key -> a).toMap

or if you're gung ho about avoiding constructing an intermediate sequence of tuples:

val map: Map[Int, A] = seq.map(a => a.key -> a)(collection.breakOut)