Reputation: 1178
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?
Upvotes: 6
Views: 3952
Reputation: 20760
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()
.
Upvotes: 11
Reputation: 417
You can try this .by which we can remove the comma(,) at end. Hope this helps you.
Map<String,String> s= new LinkedHashMap<String,String>();
s.put("1", "A");
s.put("2", "B");
s.put("3", "C");
StringBuffer sb = new StringBuffer();
String ans=null;
for (String keyinside: s.keySet()) {
sb.append(keyinside + " " + s.get(keyinside) + ", ").toString();
}
System.out.println(sb);
ans=sb.substring(0, sb.length()-2).toString();
System.out.println(ans);
Note: you can refer How to remove the last character from a string?
Upvotes: 0
Reputation: 2288
Take a counter which increments in every iteration and get a if condition which checks whether it is iterating the last time
A simple trick is
int i = 0 ;
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside));
if((i+1)<values.keySet().size()){
string.append(", ");
}
i++;
}
Also I suggest you to use StringBuilder if thread safety is not a concern
Upvotes: 1
Reputation: 5578
I quite like Joiner
from Google collections library. You could just do this:
on(",").withKeyValueSeparator(" ").join(values);
on
is statically imported from com.google.common.base.Joiner
.
If you use Maven, just add a dependency:
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
Upvotes: 1
Reputation: 393936
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).
Upvotes: 1