使用键和值将HashMap转换为String

时间:2018-08-10 09:18:10

标签: java string hashmap

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

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

4 个答案:

答案 0 :(得分:6)

您可以使用流:

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("&"));

答案 1 :(得分:3)

尝试一下:

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();

答案 2 :(得分:1)

输出Map::toString与所需的输出没有太大不同。比较:

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

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

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

答案 3 :(得分:0)

steps{
     shell('Results=${BUILD_LOG_REGEX, regex="^Results: \\[", linesBefore=0, 
           linesAfter=0, showTruncatedLines=false})
     shell('echo $Results')
}
相关问题