First of all you don't need two StringBuilders, so instead of
StringBuilder sb1 = ..
for(..){
StringBuilder sb2 = ...
//fill sb2
sb1.append(sb2);
}
you should use
StringBuilder sb1 = ..
for(..){
//add all you want to sb1
sb1.append(..)
sb1.append(..)
}
Next thing is that you don't ever want to do
sb.appent("foo" + x + "bar");
because it is same as
sb.append(new StringBuilder("foo").append(x).append("bar").toString())
which is very ineffective because:
- you are creating separate StringBuilder each time you do so
- this new StringBuilder needs to unnecessary call
toString method which has to copy all characters to new String which will later be copied to builder, instead of calling append(StringBuilder) and copy its characters directly.
So instead of sb.appent("foo" + x + "bar"); always write
sb.appent("foo").append(x).append("bar");
Now lets go back to your main problem. Since your code doesn't have declaration of line variable I am assuming that by
String[] abc = line.split("\t");
you mean
String[] abc = allLines.get(i).split("\t");
So your code can look like
StringBuilder temp = new StringBuilder();
for (int i = 0; i < allLines.size(); i++) {
String[] abc = allLines.get(i).split("\t");
temp.append("{id: \"").append(abc[0]).append("\", ");
temp.append("name: \"").append(abc[1]).append("\"}");
if (i < allLines.size() - 1)
temp.append(", ");
}
System.out.println("result : " + temp.toString());
stringBuilder.append("foo" + x)since because of concatenation this code is same asstringBuilder.append(new StringBuilder("foo).append(x).toString()), so as you see it kind of negates purpose of havingstringBuilder. Instead usestringBuilder.append("foo").append(x).