Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 457
Jesper Avatar asked May 27 '10 21:05

Jesper


People also ask

How do I convert a list to map in Scala?

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.

What is Scala seq?

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.


2 Answers

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 
like image 90
Seth Tisue Avatar answered Sep 23 '22 06:09

Seth Tisue


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 }: _*) 
like image 40
Daniel Spiewak Avatar answered Sep 23 '22 06:09

Daniel Spiewak