Converting a Java Map object to a Properties object
36,363
Solution 1
Use Properties::putAll(Map<String,String>)
method:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Properties properties = new Properties();
properties.putAll(map);
Solution 2
you also can use apache commons-collection4
org.apache.commons.collections4.MapUtils#toProperties(Map<K, V>)
example:
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);
see javadoc
Solution 3
You can do this with Commons Configuration:
Properties props = ConfigurationConverter.getProperties(new MapConfiguration(map));
http://commons.apache.org/configuration
Solution 4
Try MapAsProperties
from Cactoos:
import org.cactoos.list.MapAsProperties;
import org.cactoos.list.MapEntry;
Properties pros = new MapAsProperties(
new MapEntry<>("foo", "hello, world!")
new MapEntry<>("bar", "bye, bye!")
);
Author by
Joel
Updated on July 09, 2022Comments
-
Joel almost 2 years
Is anyone able to provide me with a better way than the below for converting a Java Map object to a Properties object?
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()); }
Thanks