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

tom*_*maj 16 java dictionary java-8 java-stream

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

"问题"

让我们说我想加入url属性String.在Guava我会这样做:

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);
Run Code Online (Sandbox Code Playgroud)

凡result为a=1&b=2&c=3.

题

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

Ale*_* C. 33

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

import static java.util.stream.Collectors.joining;

String s = attributes.entrySet()
                     .stream()
                     .map(e -> e.getKey()+"="+e.getValue())
                     .collect(joining("&"));
Run Code Online (Sandbox Code Playgroud)

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

String s = attributes.entrySet()
                     .stream()
                     .map(Object::toString)
                     .collect(joining("&"));
Run Code Online (Sandbox Code Playgroud)

  • 请注意,虽然`HashMap`条目实际上是以`key = value`格式打印的,但是从未指定过,因此依赖这个事实是不好的做法. (9认同)