将Java Map对象转换为Properties对象

Joe*_*oel 29 java properties map

是否有人能够为我提供比下面更好的方法将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());
    }
Run Code Online (Sandbox Code Playgroud)

谢谢

Bor*_*vić 73

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

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

Properties properties = new Properties();
properties.putAll(map);
Run Code Online (Sandbox Code Playgroud)


fei*_*ong 5

你也可以使用apache commons-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);
Run Code Online (Sandbox Code Playgroud)

见javadoc

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