0

I'm trying to do something like:

{"semaforo":"icbc"},{"semaforo":"pepito"}

I have the following code:

for (Iterator it = semaforosMiddleware.iterator(); it.hasNext();) {
    KeyMapMediciones semaforoMiddleware = (KeyMapMediciones) it.next();
    jsonFamilias.append("{\"semaforo\":\"" + semaforoMiddleware.getAplicacion() + "\"}");
    if (it.hasNext()) {
        jsonFamilias.append(",");
    }
}

But I get output like:

{"semaforo":"icbc"},{"semaforo":"pepito"},

I don't want the final comma (",") after the last element. What can I do?

Edd
  • 3,724
  • 3
  • 26
  • 33
  • Have a look at [Guava's Joiner](https://code.google.com/p/guava-libraries/wiki/StringsExplained) – wjans Aug 04 '15 at 12:54

6 Answers6

13

The nicest and simplest trick I learned on this site:

String separator = "";
for (String s : coll) {
   buf.append(separator).append(s);
   separator = ",";
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

The code you posted works fine. Here's a simplified runnable example:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class Test {
    public static void main(String... args){

        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");

        StringBuilder sb = new StringBuilder();

        for (Iterator<String> it = list.iterator(); it.hasNext();) {
            String element = it.next();
            sb.append(element);
            if(it.hasNext()){
                sb.append(", ");
            }
        }

        System.out.println(sb.toString()); //prints: one, two, three

    }
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
3

Find below a Java 8 solution.

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("one");
    list.add("two");
    list.add("three");

    String toString = list.stream().collect(Collectors.joining(", "));
    System.out.println("toString = " + toString);
}

output

toString = one, two, three
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
1

You can check for the first element instead (i.e. add a comma before each element except the first element) :

boolean first = true;
for (Iterator it = semaforosMiddleware.iterator(); it.hasNext();) {
    if(!first){
        jsonFamilias.append(",");
    } else {
        first = false;
    }
    KeyMapMediciones semaforoMiddleware = (KeyMapMediciones) it.next();
    jsonFamilias.append("{\"semaforo\":\"" + semaforoMiddleware.getAplicacion() + "\"}");
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Alternatively, you can also do:

String jsonFamilias = semaforosMiddleware.stream()
                        .map(s -> "{\"semaforo\":\"" + s.getAplicacion() + "\"}")
                        .collect(Collectors.joining(","));
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
0
StringBuilder stringBuilder = new StringBuilder("");
stringBuilder.append(Joiner.on(", ").join(semaforosMiddleware));
String resultString = stringBuilder.toString();

The use of a Joiner makes these scenarios much easier to handle.

GregH
  • 5,125
  • 8
  • 55
  • 109