Most elegant way to join a Map to a String in Java 8
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("&"));
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