Convert HashMap.toString() back to HashMap in Java

Viewed 109675

I put a key-value pair in a Java HashMap and converted it to a String using the toString() method.

Is it possible to convert this String representation back to a HashMap object and retrieve the value with its corresponding key?

Thanks

12 Answers

You can make use of Google's "GSON" open-source Java library for this,

Example input (Map.toString) : {name=Bane, id=20}

To Insert again in to HashMap you can use below code:

yourMap = new Gson().fromJson(yourString, HashMap.class);

That's it Enjoy.

(In Jackson Library mapper It will produce exception "expecting double-quote to start field name")

Using ByteStream can convert the String but it can encounter OutOfMemory exception in case of large Strings. Baeldung provides some nice solutions in his pot here : https://www.baeldung.com/java-map-to-string-conversion

Using StringBuilder :

public String convertWithIteration(Map<Integer, ?> map) {
StringBuilder mapAsString = new StringBuilder("{");
for (Integer key : map.keySet()) {
    mapAsString.append(key + "=" + map.get(key) + ", ");
}
mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
return mapAsString.toString(); }

Please note that lambdas are only available at language level 8 and above Using Stream :

public String convertWithStream(Map<Integer, ?> map) {
String mapAsString = map.keySet().stream()
  .map(key -> key + "=" + map.get(key))
  .collect(Collectors.joining(", ", "{", "}"));
return mapAsString; }

Converting String Back to Map using Stream :

public Map<String, String> convertWithStream(String mapAsString) {
Map<String, String> map = Arrays.stream(mapAsString.split(","))
  .map(entry -> entry.split("="))
  .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
return map; }
Related