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

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

Leave a Comment