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?
To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
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
Map over your Seq
and produce a sequence of tuples. Then use those tuples to create a Map
. Works in all versions of Scala.
val map = Map(seq map { a => a.key -> a }: _*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With