Java中的Map集合与String的相互转化
public class StringMapChange {
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>(3);
map.put("name","小明");
map.put("sex","男");
map.put("age","16");
map.put("qer","放大");
String str1 = getMapToString(map);
System.out.println(str1);
try {
Map<String, Object> map1 = getStringToMap(str1);
System.out.println(map1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMapToString(Map<String,Object> map){
Set<String> keySet = map.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
System.out.println(keySet);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
if ((String.valueOf(map.get(keyArray[i]))).trim().length() > 0) {
sb.append(keyArray[i]).append(":").append(String.valueOf(map.get(keyArray[i])).trim());
}
if(i != keyArray.length-1){
sb.append(",");
}
}
return sb.toString();
}
public static Map<String,Object> getStringToMap(String str){
String[] str1 = str.split(",");
Map<String,Object> map = new HashMap<>();
for (int i = 0; i < str1.length; i++) {
String[] str2 = str1[i].split(":");
map.put(str2[0],str2[1]);
}
return map;
}
}