【问题标题】:Converting a Java Map object to a Properties object将 Java Map 对象转换为 Properties 对象
【发布时间】:2011-12-23 14:15:01
【问题描述】:

有没有人能提供比下面更好的方法来将 Java Map 对象转换为 Properties 对象?

    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("key", "value");

    Properties properties = new Properties();

    for (Map.Entry<String, String> entry : map.entrySet()) {
        properties.put(entry.getKey(), entry.getValue());
    }

谢谢

【问题讨论】:

标签: java map properties


【解决方案1】:

使用Properties::putAll(Map&lt;String,String&gt;)方法:

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");

Properties properties = new Properties();
properties.putAll(map);

【讨论】:

  • 来自 javadocs:强烈建议不要使用它们,因为它们允许调用者插入键或值不是字符串的条目。此外,如果映射碰巧有具有空值的键,那么这将导致 NPE。
【解决方案2】:

Cactoos 尝试MapAsProperties

import org.cactoos.list.MapAsProperties;
import org.cactoos.list.MapEntry;
Properties pros = new MapAsProperties(
  new MapEntry<>("foo", "hello, world!")
  new MapEntry<>("bar", "bye, bye!")
);

【讨论】:

    【解决方案3】:

    你也可以使用 apache commons-collection4

    org.apache.commons.collections4.MapUtils#toProperties(Map&lt;K, V&gt;)

    示例:

    Map<String, String> map = new LinkedHashMap<String, String>();
    
    map.put("name", "feilong");
    map.put("age", "18");
    map.put("country", "china");
    
    Properties properties = org.apache.commons.collections4.MapUtils.toProperties(map);
    

    参见 javadoc

    https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MapUtils.html#toProperties(java.util.Map)

    【讨论】:

      【解决方案4】:

      您可以使用 Commons 配置来做到这一点:

      Properties props = ConfigurationConverter.getProperties(new MapConfiguration(map));
      

      http://commons.apache.org/configuration

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        • 1970-01-01
        • 2015-08-30
        • 1970-01-01
        • 2020-03-16
        • 1970-01-01
        相关资源
        最近更新 更多