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
Here if the user object has fields which are transient, they will be lost in the process. 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. Here is the sample code with explanation for Serialization.
In order to convert strings to HashMap, the process is divided into two parts: The input string is converted to an array of strings as output. Input as an array of strings is converted to HashMap.
HashMap get() Method in Java HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
The toString() method of ConcurrentHashMap class returns a string representation of this map. The string representation consists of a list of key-value mappings (in no particular order) enclosed in braces ("{}").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With