Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce a comma separated list using StringBuilder

Tags:

java

Following is my scenario, though I have achieved the desired output but I want it to be a decent and optimized code.

String arr[]={"we","er","rtt","yu","uu","ii"};

      StringBuilder strcat = new StringBuilder();

      for(int i1=0;i1<arr.length;i1++)
      {
          // Some processing
         strcat.append(arr[i1]);

         if(arr.length-1!=i1)
         {

              strcat.append(",");
         }
      }

     System.out.println("Value:"+strcat);

I have String[] array and some processing, after processing I want to append the values with comma(,). the problem is comma , it appends to last values also, that I don’t want, I have applied a logic. I don’t know whether it is correct.but output is correct.Please do correct me if I am wrong and do suggest if it has any other means to achieve.

like image 232
user_vs Avatar asked Oct 07 '15 08:10

user_vs


2 Answers

Nice trick I learned here

String SEPARATOR = "";
for(int i1=0;i1<arr.length;i1++)
{
    // Some processing
    strcat.append(SEPARATOR);
    strcat.append(arr[i1]);
    SEPARATOR = ",";
}
like image 59
Jordi Castilla Avatar answered Oct 07 '22 18:10

Jordi Castilla


If you're using Java 8, there's already support for this in the String class

String result = String.join(",", arr);

will result in

"we,er,rtt,yu,uu,ii"
like image 26
Steve Chaloner Avatar answered Oct 07 '22 19:10

Steve Chaloner