Build an Array of StringBuffer with x elements from a List of n elements I have an initial list that contains: 1,2,3,4,5,6,7 I want to create an array of StringBuffer that contains only 3 items per element as StringBuffer(String):

1,2,3
4,5,6
7


Initially I resolved this problem as in the following example, but I don't want to use another list to do that:

List accounts = new ArrayList();
List&lt;Person&gt; listOfObjects = results.getResults();
for(Person p: listOfObjects) {
   String persAccount = p.getAccount();
   accounts.add(persAccount);
}
String s = listToString(accounts);

public String listToString(List list) {
 StringBuffer b = new StringBuffer();
    for (int i = 0; i &lt; list.size(); i++) {
        b.append(String.valueOf(list.get(i)));
        if (i &lt; list.size()-1)
            b.append(',').toString();
    }
    return b.toString();
}


I think that an efficent way will be to create a StringBuffer and append all values in the for block.(3 by 3).

How can I do it in an efficient way?
StringBuffer

The first thing that comes to mind is the fact that you're using a StringBuffer instead of a StringBuilder. A StringBuffer is synchronized which means it has the additional overhead that comes with it. Unless you are doing this in a multithreaded environment that affects this piece of code, switching to a StringBuilder will be a good improvement.

ToString

Inside your loop you do b.append(',').toString(). Since you never do anything with the String that it returns, you are essentially needlessly creating a String each time it is hit.

Strongly typed collections

You have the collection accounts defined as List accounts = new ArrayList();: there is no type specified. 

Proper handling would be List&lt;Account&gt; accounts = new ArrayList&lt;&gt;(); so you're working with Person objects instead of general Objects.



This is aside from any remarks on whether or not your code fits your problem description, as @rolfl states. I don't see where you split it in sublists of 3 elements.