java mapString转换成Map类型

/**
 * 将Map字符串转换为Map
 *
 * @param str Map字符串
 * @return Map
 */
public static Map<String,String> mapStringToMap(String str){
    str = str.substring(1, str.length()-1);
    String[] strs = str.split(",");
    Map<String,String> map = new HashMap<String, String>();
    for (String string : strs) {
        String key = string.split("=")[0];
        String value = string.split("=")[1];
        // 去掉头部空格
        String key1 = key.trim();
        String value1 = value.trim();
        map.put(key1, value1);
    }
    return map;
}

public static void main(String[] args) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");
    System.out.println("source: " + map.toString());

    String mapStr = map.toString();
    Map<String, String> newMap = mapStringToMap(mapStr);
    System.out.println("transfer: " + map.toString());
}

执行结果:

source: {key1=value1, key2=value2, key3=value3}
transfer: {key1=value1, key2=value2, key3=value3}

 

posted @ 2023-01-19 15:04  锐洋智能  阅读(1424)  评论(0编辑  收藏  举报