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?
list.map(i => i.key -> i.value).toMap
Also:
Map(list map (i => i.key -> i.value): _*)
To create from a collection (remember NOT to have a new
keyword)
val result: HashMap[Int, Int] = HashMap(myCollection: _*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With