Gigatron
Gigatron

Reputation: 2055

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?

Upvotes: 12

Views: 12045

Answers (3)

samthebest
samthebest

Reputation: 31515

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

val result: HashMap[Int, Int] = HashMap(myCollection: _*)

Upvotes: 6

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

Also:

Map(list map (i => i.key -> i.value): _*)

Upvotes: 9

Luigi Plinge
Luigi Plinge

Reputation: 51099

list.map(i => i.key -> i.value).toMap

Upvotes: 25

Related Questions