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,636
  • 3
  • 25
  • 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
  • 188,298
  • 27
  • 302
  • 416
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
  • 40,517
  • 9
  • 64
  • 103
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
  • 21,527
  • 3
  • 48
  • 60
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
  • 374,785
  • 51
  • 663
  • 734
0

Alternatively, you can also do:

String jsonFamilias = semaforosMiddleware.stream()
                        .map(s -> "{\"semaforo\":\"" + s.getAplicacion() + "\"}")
                        .collect(Collectors.joining(","));
Jean Logeart
  • 50,693
  • 11
  • 81
  • 116
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
  • 4,772
  • 6
  • 43
  • 98