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

1

3 Answers 3

8

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Nice one line solution +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.
@ Simon - Using java 6 version. So I tried the other solution which is working. Thanks anyways.
Or, more compactly, String.join(",", cntList);. See String.join.
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));
}

Comments

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

3 Comments

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 nice thinking. Will add to the answer.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.