map转string与string转map
程序员文章站
2024-02-15 19:30:28
...
public static String mapToString(Map<String,String> map){
//获取所有map集合的key
Set<String> keySet = map.keySet();
//将set集合转换为数组
String[] arr = keySet.toArray(new String[keySet.size()]);
//给数组排序(升序)
Arrays.sort(arr);
//拼接
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if(map.get(arr[i]).trim().length()>0){
sb.append(arr[i]).append("=").append(map.get(arr[i]).trim());
}
if(i != arr.length-1){
sb.append("&");
}
}
return sb.toString();
}
public static Map<String,String> stringToMap(String str){
if(null == str || "".equals(str)){
return null;
}
String[] arr = str.split("&");
//设置hashMap的长度
int length = arr.length % 2 == 0 ? arr.length : arr.length + 1;
Map<String,String> map = new HashMap<String,String>();
for (int i = 0; i < arr.length; i++) {
String[] keyValue = arr[i].split("=");
map.put(keyValue[0],keyValue[1]);
}
return map;
}