将 Java Map 对象转换为属性对象

2022-09-01 02:16:34

有没有人能够为我提供比下面更好的方法将Java Map对象转换为属性对象?

    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());
    }

谢谢


答案 1

使用方法:Properties::putAll(Map<String,String>)

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

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

答案 2

你也可以使用apachecommons-collection4

org.apache.commons.collections4.MapUtils#toProperties(Map<K, V>)

例:

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)