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
To convert a Map to an object, call the Object. fromEntries() method passing it the Map as a parameter, e.g. const obj = Object. fromEntries(map) . The Object.
In Java, you can use the Jackson library to convert a Java object into a Map easily.
We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.
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);
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
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MapUtils.html#toProperties(java.util.Map)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With