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<Person> 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 < list.size(); i++) {
        b.append(String.valueOf(list.get(i)));
        if (i < 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?

Answer

Here is a simple version of your code, where no intermediary list is being created. Just StringBuilder is used instead of StringBuffer.

   List<Person> personList = new ArrayList<>();

    personList.add(new Person(1));
    personList.add(new Person(2));
    personList.add(new Person(3));
    personList.add(new Person(4));
    personList.add(new Person(5));
    personList.add(new Person(6));
    personList.add(new Person(7));

    List<StringBuilder> stringBuilderList = new ArrayList<>();

    int numberOfIntegerPerStringBuilder = 3;

    int index = 0;
    StringBuilder stringBuilder = null;
    for (Person person : personList) {

        if (index % numberOfIntegerPerStringBuilder == 0) {
            stringBuilder = new StringBuilder();
            stringBuilderList.add(stringBuilder);
        }

        if (stringBuilder != null) {
            stringBuilder.append(person.getAccount());
            stringBuilder.append(",");
        }
        index++;
    }

    for (StringBuilder sb : stringBuilderList) {
        sb.deleteCharAt(sb.lastIndexOf(","));
        System.out.println(sb.toString());
    }

Leave a Reply

Your email address will not be published. Required fields are marked *