24, "y" -> 25, "z" -6ren">
gpt4 book ai didi

java - 如何将Map转换为Java.util.Properties?

转载 作者:行者123 更新时间:2023-12-02 10:51:30 24 4
gpt4 key购买 nike

有没有办法从Map转换为java.util.Properties

例如,我想将以下Map转换为java.util.Properties:

Map("x" -> 24, "y" -> 25, "z" -> 26)

最佳答案

您可以使用 Properties 中的 putAll,但它需要 Java 的映射,因此您还需要进行转换:

import scala.collection.JavaConverters._ 

val m = Map("x" -> 24, "y" -> 25, "z" -> 26)
val properties = new Properties()
properties.putAll(m.mapValues(_.toString).asJava)

正如MarioGalic在评论中注意到的那样,存储在属性中的所有值都应该是字符串(即使理论上您可以存储任何对象)。来自文档:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

因此,您可能需要调用 mapValues(_.toString):

properties.putAll(m.mapValues(_.toString).asJava)

关于java - 如何将Map转换为Java.util.Properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com