在Java 8中将Map连接到String的最优雅方式

我喜欢番石榴 ,我会继续使用番石榴。 但是,在有意义的地方,我尝试使用Java 8中的“新东西”。

“问题”

假设我想在String加入url属性。 在Guava我会这样做:

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

resulta=1&b=2&c=3

Java 8 (没有任何第三方库)中,最优雅的方法是什么?

您可以获取地图条目集的流,然后将每个条目映射到所需的字符串表示forms,使用Collectors.joining(CharSequence delimiter)它们连接到单个字符串中。

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

但是由于条目的toString()已经以key=value格式输出其内容,因此可以直接调用其toString方法:

 String s = attributes.entrySet() .stream() .map(Object::toString) .collect(joining("&"));