Q:

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?

A:

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.

