Rads Rads - 1 year ago 91
Scala Question

How to convert an array of string to hashmap in scala?

I have an array like this(The actual array is dynamic with 40values):
['t1',1, 't2', 3]

I need to convert the above to a hashmap in scala which looks like this:
{'t1' => 1, 't2' => 2}

How can I achieve this. Any help would be much appreciated. Thank you.

Answer Source

This should work. It creates pairs of adjacent entries in array and creates a map for those pairs.

val arr = Array("t1",1, "t2", 3) 
arr.grouped(2).map(a => a(0) -> a(1)).toMap  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download