20

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.

Frank S. Thomas
  • 4,725
  • 2
  • 28
  • 47
Torsten Schmidt
  • 207
  • 1
  • 2
  • 6
  • 3
    Do you want b to map to 2 because it's the second in the Set? Or becasue it's the second letter in the alphabet? Sets aren't ordered, as other posters have pointed out, so the first won't work. – The Archetypal Paul Jan 31 '11 at 14:54

4 Answers4

31

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.

Adam Rabung
  • 5,232
  • 2
  • 27
  • 42
19

Here is another solution that uses a Stream of all natural numbers beginning from 1 to be zipped with your Set:

scala> Set("a", "b", "c") zip Stream.from(1) toMap
Map((a,1), (b,2), (c,3))
Frank S. Thomas
  • 4,725
  • 2
  • 28
  • 47
7

toMap only works if the Set entries are key/value pairs (e.g. Set(("a",1),("b",2),("c",3))).

To get what you want, use zipWithIndex:

Set("a","b","c") zipWithIndex
// Set[(String, Int)] = Set((a,0), (b,1), (c,2))

or (as in you original question):

Set("a","b","c") zip (1 to 3) toMap
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
GClaramunt
  • 3,148
  • 1
  • 21
  • 35
3

This would also work:

(('a' to 'c') zip (1 to 3)).toMap
Viktor Nordling
  • 8,694
  • 4
  • 26
  • 23