Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...