Convert a Map to a Properties (or vice versa)Tag(s): Language


Map to Properties
 public static Properties mapToProperties(Map<String, String> map) {
   Properties p = new Properties();
   Set<Map.Entry<String,String>> set = map.entrySet();
   for (Map.Entry<String,String> entry : set) {
     p.put(entry.getKey(), entry.getValue());
   }
   return p;
 }
or simply
Map<string,string> map = ...
Properties props = new Properties();
props.putAll(map);

Properties to Map

 public static Map<String, String> propertiesToMap(Properties props) {
   HashMap<String, String> hm = new HashMap<String,String>();
   Enumeration<Object> e = props.keys();
   while (e.hasMoreElements()) {
     String s = (String)e.nextElement();
     hm.put(s, props.getProperty(s));
   }
   return hm;
 }

blog comments powered by Disqus