从Java属性获取Scala映射

Don*_*zie 12 collections scala map scala-java-interop

我试图使用java Iterators和/或Enumerations将环境变量拉入scala脚本,并意识到Frankenstein博士可能会声称为parentage,所以我从丑陋的树中攻击了以下内容:

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())
}
Run Code Online (Sandbox Code Playgroud)

例如,打印所述相同的环境

props.keySet.toList.sortWith(_ < _).foreach{k =>
  println(k+(" " * (30 - k.length))+" = "+props(k))
}
Run Code Online (Sandbox Code Playgroud)

拜托,请不要设置抛光这个t $ #d,只是告诉我scala gem,我确信这种情况存在(即java Properties - > scala.Map),在此先感谢; @)

Sar*_*ath 8

Scala 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)
Run Code Online (Sandbox Code Playgroud)


Dan*_*ral 7

Scala 2.7:

val props = Map() ++ scala.collection.jcl.Conversions.convertMap(System.getProperties).elements
Run Code Online (Sandbox Code Playgroud)

虽然这需要一些类型转换.让我继续努力吧.

val props = Map() ++ scala.collection.jcl.Conversions.convertMap(System.getProperties).elements.asInstanceOf[Iterator[(String, String)]]
Run Code Online (Sandbox Code Playgroud)

好的,这很容易.让我现在开始工作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]])
Run Code Online (Sandbox Code Playgroud)

当然,可以通过几次进口来减少冗长度.首先,请注意Map2.8将是一个可变的地图.好的一面是,如果你转换回地图,你将获得原始对象.

现在,我不知道为什么Properties实现Map<Object, Object>,因为javadocs清楚地说明了键和值String,但是你去了.必须进行类型转换使得隐式选项的吸引力降低.在这种情况下,替代方案是最简洁的.

编辑

2.8阶只是获取从隐式转换Propertiesmutable.Map[String,String],这使得大多数代码没有实际意义的.


iwe*_*ein 7

在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} 
Run Code Online (Sandbox Code Playgroud)

从可变映射到不可变映射是在其上调用toMap的问题.

  • 刚刚意识到这是我要求的Scala Map的属性转换,但是Scala 2.10也有一个sys.props方法来访问系统属性. (2认同)