Convert HashMap.toString() back to HashMap in Java

2020-02-08 05:32发布

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

标签: java hashmap
12条回答
SAY GOODBYE
2楼-- · 2020-02-08 05:34

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 to JSONObject jsonObj

JSONObject jsonObj = new JSONObject(jsonString);
Iterator it = jsonObj.keys();

while(it.hasNext())
{
    String key = it.next().toString();
    String value = jsonObj.get(key).toString();
}
查看更多
Root(大扎)
3楼-- · 2020-02-08 05:34

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; }
查看更多
闹够了就滚
4楼-- · 2020-02-08 05:39

You cannot revert back from string to an Object. So you will need to do this:

HashMap<K, V> map = new HashMap<K, V>();

//Write:
OutputStream os = new FileOutputStream(fileName.ser);
ObjectOutput oo = new ObjectOutputStream(os);
oo.writeObject(map);
oo.close();

//Read:
InputStream is = new FileInputStream(fileName.ser);
ObjectInput oi = new ObjectInputStream(is);
HashMap<K, V> newMap = oi.readObject();
oi.close();
查看更多
再贱就再见
5楼-- · 2020-02-08 05:46

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.

查看更多
男人必须洒脱
6楼-- · 2020-02-08 05:46

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")

查看更多
虎瘦雄心在
7楼-- · 2020-02-08 05:48

toString() approach relies on implementation of toString() 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

private static String serialize(Serializable o) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);
    oos.close();
    return Base64.getEncoder().encodeToString(baos.toByteArray());
}

deserialize String back to Object

private static Object deserialize(String s) throws IOException,
        ClassNotFoundException {
    byte[] data = Base64.getDecoder().decode(s);
    ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(data));
    Object o = ois.readObject();
    ois.close();
    return o;
}

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.

public void sayHello(Map m){

}
//calling block  
Map  hm = new HashMap();
sayHello(hm);
查看更多
登录 后发表回答