Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Java Map object to a Properties object

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

like image 613
Joel Avatar asked Nov 07 '11 12:11

Joel


People also ask

How do you turn a Map into an object?

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.

Can we convert object to Map in Java?

In Java, you can use the Jackson library to convert a Java object into a Map easily.

Can we convert Map to list in Java?

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.


2 Answers

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); 
like image 174
Boris Pavlović Avatar answered Oct 02 '22 17:10

Boris Pavlović


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)

like image 29
feilong Avatar answered Oct 02 '22 15:10

feilong