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

前端 未结 2 827
萌比男神i
萌比男神i 2020-12-03 10:33

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\"

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 11:04

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

提交回复
热议问题