是否有人能够为我提供比下面更好的方法将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());
}
由于
答案 0 :(得分:67)
使用Properties::putAll(Map<String,String>)
方法:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Properties properties = new Properties();
properties.putAll(map);
答案 1 :(得分: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);
参见javadoc
答案 2 :(得分:2)
您可以使用Commons Configuration执行此操作:
Properties props = ConfigurationConverter.getProperties(new MapConfiguration(map));
答案 3 :(得分:1)
import org.cactoos.list.MapAsProperties;
import org.cactoos.list.MapEntry;
Properties pros = new MapAsProperties(
new MapEntry<>("foo", "hello, world!")
new MapEntry<>("bar", "bye, bye!")
);
答案 4 :(得分:-1)
简单使用putAll()
Properties pro = new Properties();
pro.putAll(myMapObject);
因为它接受Map作为输入。