Scala 映射到 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10439605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala map to HashMap
提问by Pablo Fernandez
Given a Listof Personobjects of this class:
给定一个此类List的Person对象:
class Person(val id : Long, val name : String)
class Person(val id : Long, val name : String)
What would be the "scala way" of obtaining a (java) HashMap with idfor keys and namefor values?
获取带有id键和name值的(java)HashMap 的“scala 方式”是什么?
If the best answer does not include using .map, please provide an example with it, even if it's harder to do.
如果最佳答案不包括 using .map,请提供一个示例,即使它更难做到。
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
回答by missingfaktor
import collection.JavaConverters._
val map = personList.map(p => (p.id, p.name)).toMap.asJava
personListhas typeList[Person].After
.mapoperation, 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.
personList有类型List[Person]。之后
.map的操作,你List[Tuple2[Long, String]](通常写作,List[(Long, String)])。之后
.toMap,你得到Map[Long, String]。并且
.asJava,顾名思义,将其转换为 Java 映射。
You don't need to define .getName, .getid. .nameand .idare already getter methods. The value-access like look is intentional, and follows uniform access principle.
您不需要定义.getName, .getid。.name并且.id已经是 getter 方法。类似价值访问的外观是有意的,并遵循统一访问原则。
回答by 9000
How about this:
这个怎么样:
- preallocate enough entries in the empty
HashMapusingpersonList's size, - run the
foreachloop, - if you need immutability,
return java.collections.unmodifiableMap(map)?
- 在空中预先分配足够的条目
HashMapusingpersonList的大小, - 运行
foreach循环, - 如果你需要不变性,
return java.collections.unmodifiableMap(map)?
This approach creates no intermediate objects. Mutable state is OK when it's confined to one local object — no side effects anyway :)
这种方法不创建中间对象。当可变状态仅限于一个本地对象时,它是可以的——无论如何都没有副作用:)
Disclaimer: I know very little Scala, so be cautious upvoting this.
免责声明:我对 Scala 知之甚少,因此请谨慎投票。

