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
personList
has typeList[Person]
.After
.map
operation, you getList[Tuple2[Long, String]]
(usually written as,List[(Long, String)]
).After
.toMap
, you getMap[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.