Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Convert Set to Map

Tags:

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.

like image 984
Torsten Schmidt Avatar asked Jan 31 '11 13:01

Torsten Schmidt


People also ask

How to convert list to map in Scala?

To convert a list into a map in Scala, we use the toMap method. We must remember that a map contains a pair of values, i.e., key-value pair, whereas a list contains only single values. So we have two ways to do so: Using the zipWithIndex method to add indices as the keys to the list.

What is Scala map function?

Advertisements. map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.


2 Answers

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.

like image 197
Adam Rabung Avatar answered Sep 22 '22 11:09

Adam Rabung


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))
like image 24
Frank S. Thomas Avatar answered Sep 20 '22 11:09

Frank S. Thomas