Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a HashMap in Scala from a list of objects without looping

I have a List of objects, each object with two fields of interest which I'll call "key" and "value". From that I need to build a HashMap made up of entries where "key" maps to "value".

I know it can be done by looping through the list and calling hmap.put(obj.key, obj.value) for every item in the list. But somehow it "smells" like this can be done in one simple line of code using map or flatMap or some other mix of Scala's List operations, with a functional construct in there. Did I "smell" right, and how would it be done?

like image 401
Gigatron Avatar asked Oct 31 '11 00:10

Gigatron


3 Answers

list.map(i => i.key -> i.value).toMap
like image 106
Luigi Plinge Avatar answered Sep 22 '22 02:09

Luigi Plinge


Also:

Map(list map (i => i.key -> i.value): _*)
like image 42
Daniel C. Sobral Avatar answered Sep 25 '22 02:09

Daniel C. Sobral


To create from a collection (remember NOT to have a new keyword)

val result: HashMap[Int, Int] = HashMap(myCollection: _*)
like image 39
samthebest Avatar answered Sep 24 '22 02:09

samthebest