scala - 从 Java 属性获取 Scala 映射

标签 scala collections map scala-java-interop

我试图使用 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())
}

例如打印上述相同的环境
props.keySet.toList.sortWith(_ < _).foreach{k =>
  println(k+(" " * (30 - k.length))+" = "+props(k))
}

拜托,请不要着手完善这个 t$#d,只需向我展示我确信在这种情况下存在的 scala gem(即 java 属性 --> scala.Map),提前致谢;@)

最佳答案

斯卡拉 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)

关于scala - 从 Java 属性获取 Scala 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2016268/

相关文章:

scala - 如何在 Scala 中将 DataFrame 转换为 DynamicFrame 对象

parsing - Scala 错误编译 OptionBuilder

java - 线程从 arrayList 中删除并插入函数

ruby-on-rails - 在这种情况下,Ruby 的 map 方法如何工作?

scala - 在文本文件中写入/存储数据帧

scala - 如何在 Scala 中将阻塞 IO 包装为非阻塞

java - 集合投影和嵌套投影

scala - 如何旋转(圆形移位)Scala 集合

map - LeafletJS 标记在缩放时移动

c++ - 使用 std::map 时这些做法是否合适?