1

I have one problem when appending List values as String. I will be getting 1 or more than 1 value into the list. Then I need to append these string as one string and use a separator , for each string. But at the end also the comma is getting added. How Can I remove this at the end of the string dynamically. Here is my code:

cntList = parseXml(metadata.xml);
if (cntList.size() != 0) {
    // entryCountryMap.put(id, country);
    System.out.println("Size is  ---->" + cntList.size());
    StringBuilder sb = new StringBuilder();
    if (cntList.size() >= 2) {
        for (String s : cntList) {
            sb.append(s);
            sb.append(",");
        }
    }
    System.out.println("StringBuilder ----->" + sb.toString());
}

And my output is like this:

StringBuilder ----->All Countries,US - United States,

Please help me resolving this. Thanks - Raji

Mena
  • 47,782
  • 11
  • 87
  • 106
Rajyalakshmi S
  • 173
  • 1
  • 4
  • 16
  • 1
    What you are looking for is called Joining a string. This is explained here: [Java: convert List to a joined string](http://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-joined-string) – Thirler Jul 08 '15 at 13:27

3 Answers3

6

With java 8 it's a one liner

String.join(",", cntList);

If you need to filter the elements of the list and/or mutate the strings before joining to a single string, you can still do it in a very concise manner without loops.

cntList.stream().filter(...).map(...).collect(Collectors.joining(","));

(the ... need to be replaced by your filtering predicate and your mapper)

Simon
  • 6,293
  • 2
  • 28
  • 34
  • Nice **one line** solution +1 – maskacovnik Jul 08 '15 at 13:32
  • 1
    There is nothing telling Java 8 is being used. Also, if Java 8 is available, a `String.join()` is superior for this particular situation. – m4ktub Jul 08 '15 at 13:44
  • @ Simon - Using java 6 version. So I tried the other solution which is working. Thanks anyways. – Rajyalakshmi S Jul 08 '15 at 14:03
  • Or, more compactly, `String.join(",", cntList);`. See [String.join](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-). – VGR Jul 08 '15 at 14:28
3

I would use normal for loop. The last one append outside the for loop without comma

if (cntList.size() >= 2) {
    for (int i=0;i<cntList.size()-1;i++) {
        sb.append(cntList.get(i));
        sb.append(",");
    }
    sb.append(cntList.get(cntList.size()-1));
}
maskacovnik
  • 3,080
  • 5
  • 20
  • 26
1

Simply delete the last character:

StringBuilder sb = new StringBuilder("foo,");
System.out.println(sb.deleteCharAt(sb.length() - 1)); 

Output

foo

More dynamically, you can find the last comma by index and delete that plus anything that comes after:

sb.delete(sb.lastIndexOf(","), sb.length());

As Pshemo points out:

sb.setLength(sb.length() - 1); will actually perform better than sb.deleteCharAt(sb.length() - 1).

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
  • 1
    From what I remember `sb.deleteCharAt(sb.length() - 1)` will need to create new copy of old values without last element. It would be faster to simply set reduce length of builder `sb.setLength(sb.length() - 1);` – Pshemo Jul 08 '15 at 13:50
  • @Pshemo nice thinking. Will add to the answer. – Mena Jul 08 '15 at 13:55
  • I am not sure what you mean. `setLenght` will call `ensureCapacityInternal` which will try to expand array if new capacity is larger, but this is not the case here since we want to reduce it. – Pshemo Jul 08 '15 at 14:03