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?
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.
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.
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.
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) .
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
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 -> ----)
val map = foo zip (foo map f) toMap
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