charlesF charlesF - 1 year ago 61
Java Question

What is the best correct way to iterate through the "columns and rows" of a string matrix in Java?

I know how to do it for one string:

for (int i = 0; i < string.length(); i++){
char c = string.charAt(i);

but when I have something like a String [][] how it works?

Answer Source

If you just need to access the values then you can use for-each loops:

for (String[] row: array) {
    for (String value: row) {
        // use value

This won't work if you want to change the values. In that case you need to have the indices available. You can use traditional for loops for that (as referenced in the other answers) or, in Java 8, IntStream:

IntStream.range(0, array.length).forEach(r ->
    IntStream.range(0, array[r].length).forEach(c -> {
        // use array[r][c]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download