-2

I want to create util method which converts HashMap into long String with keys and values:

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

map.put("first_key", "first_value");
map.put("second_key", "second_value");

I need to get this end result:

first_key=first_value&second_key=second_value
Óscar López
  • 232,561
  • 37
  • 312
  • 386
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

4 Answers4

11

You can use streams:

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

Note: You should probably use an url encoding. First create a helper method like this:

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

And then use that inside of your stream to encode the key and value:

String result = map.entrySet().stream()
   .map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
   .collect(Collectors.joining("&"));
Lino
  • 19,604
  • 6
  • 47
  • 65
4

Try this:

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();
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0
map.toString().replace(",","&")
Java_Waldi
  • 924
  • 2
  • 12
  • 29
0

The output Map::toString is not much different from the output you want. Compare:

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

Just perform the right character replacement:

map.toString().replaceAll("[{ }]", "").replace(",","&")
  • "[{ }]" is regex matching all the brackets {} and the space - those to be removed (replaced with "").
  • , to be replaced with & character.
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183