将哈希映射转换为带有键和值的字符串



我想创建将HashMap转换为带有键和值的长字符串的util方法:

HashMap<String, String> map = new LinkedhashMap<>();
map.put("first_key", "first_value");
map.put("second_key", "second_value");

我需要得到这个最终结果:

first_key=first_value&second_key=second_value

您可以使用流:

String result = map.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&"));

注意:您可能应该使用 url 编码。首先创建一个帮助程序方法,如下所示:

public static String encode(String s){
try{
return java.net.URLEncoder.encode(s, "UTF-8");
} catch(UnsupportedEncodingException e){
throw new IllegalStateException(e);
}
}

然后在流中使用它来编码键和值:

String result = map.entrySet().stream()
.map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
.collect(Collectors.joining("&"));

试试这个:

StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey());
sb.append('=');
sb.append(entry.getValue());
sb.append('&');
}
sb.deleteCharAt(sb.length() - 1);
String result = sb.toString();
map.toString().replace(",","&")

输出Map::toString与您想要的输出没有太大区别。比较:

  • {first_key=first_value, second_key=second_value}
  • first_key=first_value&second_key=second_value

只需执行正确的字符替换:

map.toString().replaceAll("[{ }]", "").replace(",","&")
  • "[{ }]"是正则表达式匹配所有括号{}和空格- 要删除的括号(替换为,(。
  • &替换为CC_9字符。

最新更新