List Having Same Lengths
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2", "2_3" },
{ "3_1", "3_2", "3_3" }
};
for (int count = 0; count < values.length * values[0].length; count++) {
System.out.println(values[count % values.length][count / values[0].length]);
}
}
The expression:
count % values.length
does rotate between all rows, while the expression:
count / values[0].length
increases by one after row many iterations.
List Having Different Lengths
public static void main(String[] args) {
String[][] values = new String[][] {
{ "1_1", "1_2", "1_3" },
{ "2_1", "2_2" },
{ "3_1", "3_2", "3_3", "3_4" }
};
for (int count = 0, maxLen = 0;; count++) {
int row = count % values.length;
int col = count / values[0].length;
maxLen = Math.max(values[row].length, maxLen);
if (values[row].length > col) {
System.out.println(values[row][col]);
} else if (row + 1 == values.length && col >= maxLen) break;
}
}
The differences to the solution provided for list having same lengths are:
- fetch a value only if the current list defines the computed column.
- collect the maximum length of all lists while iterating over the values.
- stop if no list exists having defining currently computed column.