Scala map to HashMap

collectionsmapscala

Given a List of Person objects of this class:

class Person(val id : Long, val name : String)

What would be the "scala way" of obtaining a (java) HashMap with id for keys and name for values?

If the best answer does not include using .map, please provide an example with it, even if it's harder to do.

Thank you.

EDIT

This is what I have right now, but it's not too immutable:

val map = new HashMap[Long, String]
personList.foreach { p => map.put(p.getId, p.getName) }

return map

Best Answer

import collection.JavaConverters._
val map = personList.map(p => (p.id, p.name)).toMap.asJava
  • personList has type List[Person].

  • After .map operation, you get List[Tuple2[Long, String]] (usually written as, List[(Long, String)]).

  • After .toMap, you get Map[Long, String].

  • And .asJava, as name suggests, converts it to a Java map.

You don't need to define .getName, .getid. .name and .id are already getter methods. The value-access like look is intentional, and follows uniform access principle.