Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala map to HashMap

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
like image 738
Pablo Fernandez Avatar asked May 03 '12 21:05

Pablo Fernandez


People also ask

Is Scala map a HashMap?

HashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map.

How do I convert a HashMap to a Scala map?

Converting HashMap to Map In Scala, we can convert a hashmap to a map using the tomap method. Explanation: In the above code, we have created a HashMap and then convert it to a Map using the toMap method.

What does map () do in Scala?

map() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns a new collection.


1 Answers

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.

like image 55
missingfaktor Avatar answered Oct 31 '22 18:10

missingfaktor