I have the next map values:
{title=varchar(50), text=text}
I am trying to convert it into two strings like this:
StringBuffer string = new StringBuffer();
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside) + ", ");
}
But what I want here - not inlude ", " at the last iteration. How can I do it?
Short java 8 alternative:
String result = values.entrySet().stream().map(e -> e.getKey() + " " + e.getValue())
.collect(Collectors.joining(", "))
Stream.map()
to convert all entries in the map to a string description of the entry.
Note that Java 8 also finally adds the function String.join()
.
Use some indicator :
StringBuffer string = new StringBuffer();
boolean first = true;
for (String keyinside: values.keySet()) {
if (!first)
string.append (", ");
else
first = false;
string.append(keyinside + " " + values.get(keyinside));
}
BTW, it's more efficient to use StringBuilder (assuming you don't need thread safety).
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