Scala go to HashMap

Given the List of Person objects of this class:

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

What would be a scala way to get (java) a HashMap with id for keys and name for values?

If the best answer does not include using .map , give an example with it, even if it is harder to do.

Thanks.

EDIT

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

 val map = new HashMap[Long, String] personList.foreach { p => map.put(p.getId, p.getName) } return map 
+6
source share
2 answers
 import collection.JavaConverters._ val map = personList.map(p => (p.id, p.name)).toMap.asJava 
  • personList is of type List[Person] .

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

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

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

You do not need to define .getName , .getid . .name and .id are already getter methods. The value-accessible view looks intentionally and follows the principle of single access.

+11
source

How about this:

  • provide enough entries in an empty HashMap using the personList size,
  • run the foreach ,
  • If you need immutability, return java.collections.unmodifiableMap(map) ?

This approach does not create intermediate objects. Mutable state is okay when it is limited to one local object - no side effects anyway :)

Disclaimer: I know very little Scala, so be careful to do this.

+2
source

Source: https://habr.com/ru/post/914848/


All Articles