Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HashMap.toString() back to HashMap in Java

Tags:

java

hashmap

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

like image 521
Sameek Mishra Avatar asked Oct 18 '10 06:10

Sameek Mishra


People also ask

Can we convert HashMap to string?

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.

Can we convert string to HashMap in Java?

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.

How do you return a HashMap value in Java?

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.

What does HashMap toString do?

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 ("{}").


1 Answers

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.

like image 155
AlexR Avatar answered Sep 18 '22 09:09

AlexR