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)?
Use Object#toString() . String string = map. toString();
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("&"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With