1.8系列
/**
* 获得k1=v1&k2=v2 字符串
* @param map
* @return
*/
public static String getKeyAndValueStr(Map<String, String> map) {
String result = "";
try {
List<Map.Entry<String, String>> infoIds = new ArrayList<>(map.entrySet());
// 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
Collections.sort(infoIds, Comparator.comparing(Map.Entry::getKey));
// 构造签名键值对的格式
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> item : infoIds) {
if (item.getKey() != null || item.getKey() != "") {
String key = item.getKey();
String val = item.getValue();
if (!(val == "" || val == null)) {
sb.append(key + "=" + val + "&");
}
}
}
result = sb.toString().substring(0, sb.length() - 1);
} catch (Exception e) {
return null;
}
return result;
}
兼容系列
/**
* 获得k1=v1&k2=v2 字符串
* @param map
* @return
*/
public static String getKeyAndValueStr(Map<String, String> map) {
String result = "";
try {
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
// 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
// 构造签名键值对的格式
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> item : infoIds) {
if (item.getKey() != null || item.getKey() != "") {
String key = item.getKey();
String val = item.getValue();
if (!(val == "" || val == null)) {
sb.append(key + "=" + val + "&");
}
}
}
result = sb.toString().substring(0, sb.length() - 1);
} catch (Exception e) {
return null;
}
return result;
}
Joiner 方式
Map<String, String> map= new HashMap<>();
requestMap.put("aaaa", "11213");
requestMap.put("wwww", "2154");
requestMap.put("bbb", "112");
requestMap.put("efwwwww", "54541");
String string = Joiner.on("&").withKeyValueSeparator("=").join(map);
System.out.println("string = " + string);