Search code examples
javadictionaryjava-8java-stream

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)?


Solution

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