Stack Exchange
Java: Iterate and take every xth item
I tried to iterate over a set of numbers and after every 6th item, I need to do a cut. Following is the sample code:
int c = 1;
StringBuffer sb = new StringBuffer();
for(int x = 1; x < 32; x++) {
    sb.append(x+ ",");
    c++;
    if (c == 6) {
        System.out.println("ADDED TO COLLECTION: " + sb.toString());
        sb = new StringBuffer();
        c = 0;
    }
}

Output:
ADDED TO COLLECTION: 1,2,3,4,5,
ADDED TO COLLECTION: 6,7,8,9,10,11,
ADDED TO COLLECTION: 12,13,14,15,16,17,
ADDED TO COLLECTION: 18,19,20,21,22,23,
ADDED TO COLLECTION: 24,25,26,27,28,29,

Missing is Nr. 31 - how can that be achieved?

Your System.out.println is inside the if, so you only print it out once you have collected a complete set of six numbers.

Initialize c with zero not one

Your code is never executing what is inside your if statement on the last loop because your counter never reaches 6.  You'll need some additional logic to handle the case where the count of items in your last batch is less than 6.

Off-topic note but we use StringBuilder precisely to avoid concatenation. So instead of sb.append(x+ ","); you should use sb.append(x).append(',');

You can add a println at the end:
    int c = 1;
    StringBuffer sb = new StringBuffer();
    for (int x = 1; x < 32; x++) {
        sb.append(x + ",");
        c++;
        if (c == 6) {
            System.out.println("ADDED TO COLLECTION: " + sb.toString());
            sb = new StringBuffer();
            c = 0;
        }
    }
    // after the last iteration there is still something left in sb:
    System.out.println("ADDED TO COLLECTION: " + sb.toString());

You could also add a check whether there is actually something in sb and skip printing.

That works, but what if x <5? How to get the last item?

Just add this to your if statement || x == 31
You code will look like this:
int c = 1;
StringBuffer sb = new StringBuffer();
for(int x = 1; x < 32; x++) {
    sb.append(x+ ",");
    c++;
    if (c == 6 || x == 31) {
        System.out.println("ADDED TO COLLECTION: " + sb.toString());
        sb = new StringBuffer();
        c = 0;
    }
}


that doesn't work since 32 is just a dummy value and can be 5

well you can change that for your max value - 1. For example:

int c = 1; int max = 32; StringBuffer sb = new StringBuffer(); for(int x = 1; x < 32; x++) {     sb.append(x+ ",");     c++;     if (c == 6 || x == max - 1) {         System.out.println("ADDED TO COLLECTION: " + sb.toString());         sb = new StringBuffer();         c = 0;     } }
