Convert HashMap.toString() back to HashMap in Java

It will work if toString() contains all data needed to restore the object. For example it will work for map of strings (where string is used as key and value):

// create map
Map<String, String> map = new HashMap<String, String>();
// populate the map

// create string representation
String str = map.toString();

// use properties to restore the map
Properties props = new Properties();
props.load(new StringReader(str.substring(1, str.length() - 1).replace(", ", "\n")));       
Map<String, String> map2 = new HashMap<String, String>();
for (Map.Entry<Object, Object> e : props.entrySet()) {
    map2.put((String)e.getKey(), (String)e.getValue());
}

This works although I really do not understand why do you need this.

Leave a Comment