Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to join a Map to a String in Java 8

I love Guava, and I'll continue to use Guava a lot. But, where it makes sense, I try to use the "new stuff" in Java 8 instead.

"Problem"

Lets say I want to join url attributes in a String. In Guava I would do it like this:

Map<String, String> attributes = new HashMap<>(); attributes.put("a", "1"); attributes.put("b", "2"); attributes.put("c", "3");  // Guava way String result = Joiner.on("&").withKeyValueSeparator("=").join(attributes); 

Where the result is a=1&b=2&c=3.

Question

What is the most elegant way to do this in Java 8 (without any 3rd party libraries)?

like image 765
tomaj Avatar asked Oct 05 '15 07:10

tomaj


People also ask

How do I cast a map to a string in Java?

Use Object#toString() . String string = map. toString();


1 Answers

You can grab the stream of the map's entry set, then map each entry to the string representation you want, joining them in a single string using Collectors.joining(CharSequence delimiter).

import static java.util.stream.Collectors.joining;  String s = attributes.entrySet()                      .stream()                      .map(e -> e.getKey()+"="+e.getValue())                      .collect(joining("&")); 

But since the entry's toString() already output its content in the format key=value, you can call its toString method directly:

String s = attributes.entrySet()                      .stream()                      .map(Object::toString)                      .collect(joining("&")); 
like image 152
Alexis C. Avatar answered Oct 12 '22 03:10

Alexis C.