我爱Guava,我将继续使用番石榴。但是,在有意义的地方,我尝试使用 Java 8 中的“新东西”。
“问题”
假设我想在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);
result
为a=1&b=2&c=3
。
问题
在 Java 8 (没有任何第三方库)中执行此操作的最佳方法是什么?
答案 0 :(得分:27)
您可以抓取地图条目集的流,然后将每个条目映射到您想要的字符串表示形式,使用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("&"));
答案 1 :(得分:0)
public static void main(String[] args) {
HashMap<String,Integer> newPhoneBook = new HashMap(){{
putIfAbsent("Arpan",80186787);
putIfAbsent("Sanjay",80186788);
putIfAbsent("Kiran",80186789);
putIfAbsent("Pranjay",80186790);
putIfAbsent("Jaiparkash",80186791);
putIfAbsent("Maya",80186792);
putIfAbsent("Rythem",80186793);
putIfAbsent("Preeti",80186794);
}};
/**Compining Key and Value pairs and then separate each pair by some delimiter and the add prefix and Suffix*/
String keyValueCombinedString = newPhoneBook.entrySet().stream().
map(entrySet -> entrySet.getKey() + ":"+ entrySet.getValue()).
collect(Collectors.joining("," , "[","]"));
System.out.println(keyValueCombinedString);
/**
* OUTPUT : [Kiran:80186789,Arpan:80186787,Pranjay:80186790,Jaiparkash:80186791,Maya:80186792,Sanjay:80186788,Preeti:80186794,Rythem:80186793]
*
* */
String keyValueCombinedString1 = newPhoneBook.entrySet().stream().
map(Objects::toString).
collect(Collectors.joining("," , "[","]"));
System.out.println(keyValueCombinedString1);
/**
* Objects::toString method concate key and value pairs by =
* OUTPUT : [Kiran=80186789,Arpan=80186787,Pranjay=80186790,Jaiparkash=80186791,Maya=80186792,Sanjay=80186788,Preeti=80186794,Rythem=80186793]
* */
}
> Blockquote