Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Map from tuple iterable

Tags:

Constructing scala.collection.Map from other collections, I constantly find myself writing:

val map = Map(foo.map(x=>(x, f(x)))

However, this doesn't really work since Map.apply takes variable arguments only - so I have to write:

val map = Map(foo.map(x=>(x, f(x)) toSeq :_*)

to get what I want, but that seems painful. Is there a prettier way to construct a Map from an Iterable of tuples?

like image 803
themel Avatar asked Jun 29 '11 14:06

themel


People also ask

How do you access map elements in Scala?

Scala Map get() method with exampleThe get() method is utilized to give the value associated with the keys of the map. The values are returned here as an Option i.e, either in form of Some or None. Return Type: It returns the keys corresponding to the values given in the method as argument.

How do I convert a list to map in Scala?

In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.

What is iterable Scala?

Iterable: A base trait for iterable collections. This is a base trait for all Scala collections that define an iterator method to step through one-by-one the collection's elements.

What is Scala map function?

A Map is an Iterable consisting of pairs of keys and values (also named mappings or associations). Scala's Predef object offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value) .


3 Answers

Use TraversableOnce.toMap which is defined if the elements of a Traversable/Iterable are of type Tuple2. (API)

val map = foo.map(x=>(x, f(x)).toMap
like image 121
Debilski Avatar answered Sep 23 '22 04:09

Debilski


Alternatively you can use use collection.breakOut as the implicit CanBuildFrom argument to the map call; this will pick a result builder based on the expected type.

scala> val x: Map[Int, String] = (1 to 5).map(x => (x, "-" * x))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)

It will perform better than the .toMap version, as it only iterates the collection once.

It's not so obvious, but this also works with a for-comprehension.

scala> val x: Map[Int, String] = (for (i <- (1 to 5)) yield (i, "-" * i))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)
like image 20
retronym Avatar answered Sep 25 '22 04:09

retronym


val map = foo zip (foo map f) toMap
like image 38
Landei Avatar answered Sep 24 '22 04:09

Landei