从 Java 属性获取 Scala 映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2016268/
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
Getting a Scala Map from a Java Properties
提问by Don Mackenzie
I was trying to pull environment variables into a scala script using java Iterators and / or Enumerations and realised that Dr Frankenstein might claim parentage, so I hacked the following from the ugly tree instead:
我试图使用 java Iterators 和/或 Enumerations 将环境变量拉入 scala 脚本,并意识到 Frankenstein 博士可能声称出身,所以我从丑陋的树中修改了以下内容:
import java.util.Map.Entry
import System._
val propSet = getProperties().entrySet().toArray()
val props = (0 until propSet.size).foldLeft(Map[String, String]()){(m, i) =>
val e = propSet(i).asInstanceOf[Entry[String, String]]
m + (e.getKey() -> e.getValue())
}
For example to print the said same environment
例如打印上述相同的环境
props.keySet.toList.sortWith(_ < _).foreach{k =>
println(k+(" " * (30 - k.length))+" = "+props(k))
}
Please, please don't set about polishing this t$#d, just show me the scala gem that I'm convinced exists for this situation (i.e java Properties --> scala.Map), thanks in advance ;@)
拜托,请不要着手完善这个 t$#d,只需向我展示我确信在这种情况下存在的 scala gem(即 java 属性 --> scala.Map),提前致谢;@)
采纳答案by Daniel C. Sobral
Scala 2.7:
斯卡拉 2.7:
val props = Map() ++ scala.collection.jcl.Conversions.convertMap(System.getProperties).elements
Though that needs some typecasting. Let me work on it a bit more.
虽然这需要一些类型转换。让我多做一点。
val props = Map() ++ scala.collection.jcl.Conversions.convertMap(System.getProperties).elements.asInstanceOf[Iterator[(String, String)]]
Ok, that was easy. Let me work on 2.8 now...
好的,这很容易。现在让我在 2.8 上工作......
import scala.collection.JavaConversions.asMap
val props = System.getProperties() : scala.collection.mutable.Map[AnyRef, AnyRef] // or
val props = System.getProperties().asInstanceOf[java.util.Map[String, String]] : scala.collection.mutable.Map[String, String] // way too many repetitions of types
val props = asMap(System.getProperties().asInstanceOf[java.util.Map[String, String]])
The verbosity, of course, can be decreased with a couple of imports. First of all, note that Mapwill be a mutable map on 2.8. On the bright side, if you convert back the map, you'll get the original object.
当然,可以通过几个导入来减少冗长。首先,请注意这Map将是 2.8 上的可变映射。从好的方面来说,如果您转换回地图,您将获得原始对象。
Now, I have no clue why Propertiesimplements Map<Object, Object>, given that the javadocs clearly state that key and value are String, but there you go. Having to typecast this makes the implicit option much less attractive. This being the case, the alternative is the most concise of them.
现在,我不知道为什么Propertiesimplements Map<Object, Object>,因为 javadocs 清楚地说明 key 和 value 是String,但是你去了。必须对此进行类型转换使得隐式选项的吸引力大大降低。在这种情况下,替代方案是其中最简洁的。
EDIT
编辑
Scala 2.8 just acquired an implicit conversion from Propertiesto mutable.Map[String,String], which makes most of that code moot.
Scala 2.8 刚刚获得了从Propertiesto的隐式转换mutable.Map[String,String],这使得大部分代码没有实际意义。
回答by Sarath
Scala 2.10.3
斯卡拉 2.10.3
import scala.collection.JavaConverters._
//Create a variable to store the properties in
val props = new Properties
//Open a file stream to read the file
val fileStream = new FileInputStream(new File(fileName))
props.load(fileStream)
fileStream.close()
//Print the contents of the properties file as a map
println(props.asScala.toMap)
回答by iwein
In Scala 2.9.1 this is solved by implicit conversions inside collection.JavaConversions._ . The other answers use deprecated functions. The details are documented here. This is a relevant snippet out of that page:
在 Scala 2.9.1 中,这是通过 collection.JavaConversions._ 中的隐式转换解决的。其他答案使用已弃用的函数。详细信息记录在此处。这是该页面的相关片段:
scala> import collection.JavaConversions._
import collection.JavaConversions._
scala> import collection.mutable._
import collection.mutable._
scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3)
jul: java.util.List[Int] = [1, 2, 3]
scala> val buf: Seq[Int] = jul
buf: scala.collection.mutable.Seq[Int] = ArrayBuffer(1, 2, 3)
scala> val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2)
m: java.util.Map[String,Int] = {hello=2, abc=1}
Getting from a mutable map to an immutable map is a matter of calling toMap on it.
从可变映射到不可变映射是在其上调用 toMap 的问题。
回答by Vitalii Fedorenko
In Scala 2.8.1 you can do it with asScalaMap(m : java.util.Map[A, B])in a more concise way:
在 Scala 2.8.1 中,你可以用asScalaMap(m : java.util.Map[A, B])更简洁的方式做到这一点:
var props = asScalaMap(System.getProperties())
props.keySet.toList.sortWith(_ < _).foreach { k =>
println(k + (" " * (30 - k.length)) + " = " + props(k))
}
回答by Erik Kaplun
Looks like in the most recent version of Scala (2.10.2 as of the time of this answer), the preferred way to do this is using the explicit .asScalafrom scala.collection.JavaConverters:
看起来在最新版本的 Scala 中(截至本答案发布时为 2.10.2),执行此操作的首选方法是使用显式.asScalafrom scala.collection.JavaConverters:
import scala.collection.JavaConverters._
val props = System.getProperties().asScala
assert(props.isInstanceOf[Map[String, String]])

