Convert HashMap.toString() back to HashMap in Java

后端 未结 12 1729
执念已碎
执念已碎 2020-12-14 00:35

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 t

12条回答
  •  臣服心动
    2020-12-14 00:54

    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 map = new HashMap();
    // 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 map2 = new HashMap();
    for (Map.Entry e : props.entrySet()) {
        map2.put((String)e.getKey(), (String)e.getValue());
    }
    

    This works although I really do not understand why do you need this.

提交回复
热议问题