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: _*)
Share:
10,578
Gigatron
Author by

Gigatron

Updated on June 05, 2022

Comments

  • Gigatron
    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 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?

  • Luigi Plinge
    Luigi Plinge over 12 years
    I 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
    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 use breakOut.
  • Gigatron
    Gigatron over 12 years
    I'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
    Gigatron over 12 years
    OK, I got it now. Map.apply with varargs.
  • samthebest
    samthebest over 9 years
    OP wants a HashMap not a Map
  • Richard Gomes
    Richard Gomes over 7 years
    Warning: It does not support duplicated keys!
  • Richard Gomes
    Richard Gomes over 7 years
    Note: It does not support duplicated keys!