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

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, then in Scala 2.8 through 2.12:

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

or in Scala 2.13 and 3 (which don’t have breakOut, but do have a reliable .view):

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)