使用键和值将HashMap转换为String

Pet*_*zov -3 java string hashmap

我想创建一个util方法,它使用键和值将HashMap转换为long String:

HashMap<String, String> map = new LinkedhashMap<>();

map.put("first_key", "first_value");
map.put("second_key", "second_value");
Run Code Online (Sandbox Code Playgroud)

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

first_key=first_value&second_key=second_value
Run Code Online (Sandbox Code Playgroud)

Lin*_*ica 6

你可以使用流:

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

注意:您应该使用url编码.首先创建一个这样的辅助方法:

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

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

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