Scala Convert Set to Map

Torsten Schmidt picture Torsten Schmidt · Jan 31, 2011 · Viewed 18.7k times · Source

How do I convert a Set("a","b","c") to a Map("a"->1,"b"->2,"c"->3)? I think it should work with toMap.

Answer

Adam Rabung picture Adam Rabung · Jan 31, 2011

zipWithIndex is probably what you are looking for. It will take your collection of letters and make a new collection of Tuples, matching value with position in the collection. You have an extra requirement though - it looks like your positions start with 1, rather than 0, so you'll need to transform those Tuples:

Set("a","b","c")
  .zipWithIndex    //(a,0), (b,1), (c,2)
  .map{case(v,i) => (v, i+1)}  //increment each of those indexes
  .toMap //toMap does work for a collection of Tuples

One extra consideration - Sets don't preserve position. Consider using a structure like List if you want the above position to consistently work.