Scala Map from tuple iterable

themel picture themel · Jun 29, 2011 · Viewed 17.8k times · Source

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?

Answer

Debilski picture Debilski · Jun 29, 2011

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