In Scala, is there a way to take convert two lists into a Map?

Andy Hull picture Andy Hull · Feb 3, 2010 · Viewed 20.2k times · Source

I have a two lists, a List[A] and a List[B]. What I want is a Map[A,B] but I want the semantics of zip. So started out like so:

var tuplesOfAB = listOfA zip listOfB

Now I'm not sure how to construct a Map from my tuplesOfAB.

As a follow-up question, I also want to invert my map so that from a Map[A,B] I can create a Map[B,A]. Can anyone hit me with a clue-stick?

Answer

oxbow_lakes picture oxbow_lakes · Feb 3, 2010

In 2.8 this is really simple using the CanBuildFrom functionality (as described by Daniel) and using breakOut with a type instruction to the compiler as to what the result type should be:

import scala.collection.breakOut
val m = (listA zip listB)(breakOut): Map[A,B]

The following would also work:

val n: Map[A,B] = (listA zip listB)(breakOut)

And (as EastSun, below, has pointed out) this has been added to the library as toMap

val o = (listA zip listB).toMap

As for reversing the map, you can do:

val r = m.map(_.swap)(breakOut): Map[B, A]