Create a HashMap in Scala from a list of objects without looping
10,578
Solution 1
list.map(i => i.key -> i.value).toMap
Solution 2
Also:
Map(list map (i => i.key -> i.value): _*)
Solution 3
To create from a collection (remember NOT to have a new
keyword)
val result: HashMap[Int, Int] = HashMap(myCollection: _*)
Author by
Gigatron
Updated on June 05, 2022Comments
-
Gigatron about 2 years
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 usingmap
orflatMap
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? -
Luigi Plinge over 12 yearsI suppose the advantage of this is that you can specify the type of Map you need, so it's more general pattern
-
Daniel C. Sobral over 12 years@LuigiPlinge That is true. I much prefer using
.toMap
, as it is much more readable. If performance is of great concern, maybe usebreakOut
. -
Gigatron over 12 yearsI'm lost with that last part : _* I get that the underscore is a placeholder for the functional variable, but I can't see how it fits in to that expression, nor the role of the asterisk and colon in that context.
-
Gigatron over 12 yearsOK, I got it now. Map.apply with varargs.
-
samthebest over 9 yearsOP wants a
HashMap
not aMap
-
Richard Gomes over 7 yearsWarning: It does not support duplicated keys!
-
Richard Gomes over 7 yearsNote: It does not support duplicated keys!