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
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
Are you restricted to use only
HashMap
??Why can't it be so much flexible
JSONObject
you can do a lot with it.You can convert
String jsonString
toJSONObject jsonObj
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 :
Please note that lambdas are only available at language level 8 and above Using Stream :
Converting String Back to Map using Stream :
You cannot revert back from string to an Object. So you will need to do this:
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):
This works although I really do not understand why do you need this.
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:
That's it Enjoy.
(In Jackson Library mapper It will produce exception "expecting double-quote to start field name")
toString()
approach relies on implementation oftoString()
and it can be lossy in most of the cases.There cannot be non lossy solution here. but a better one would be to use Object serialization
serialize Object to String
deserialize String back to Object
Here if the user object has fields which are transient, they will be lost in the process.
old answer
Once you convert HashMap to String using toString(); It's not that you can convert back it to Hashmap from that String, Its just its String representation.
You can either pass the reference to HashMap to method or you can serialize it
Here is the description for toString() toString()
Here is the sample code with explanation for Serialization.
and to pass hashMap to method as arg.