Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java iterate over map except last iteration

Tags:

java

iteration

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?

like image 657
ovod Avatar asked Feb 26 '15 11:02

ovod


2 Answers

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().

like image 185
Thirler Avatar answered Oct 06 '22 01:10

Thirler


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).

like image 23
Eran Avatar answered Oct 05 '22 23:10

Eran