Reputation: 2055
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
Reputation: 31515
To create from a collection (remember NOT to have a new
keyword)
val result: HashMap[Int, Int] = HashMap(myCollection: _*)
Upvotes: 6