Home:ALL Converter>Improve (Row)(Col) Iteration Efficiency - Java

Improve (Row)(Col) Iteration Efficiency - Java

Ask Time:2015-01-08T04:29:07         Author:ggle

Json Formatter

I am currently writing a long class for an application I am working on. There is 2 lines of code that are constantly being repeated, however I cannot think of a quicker way to do it!

The lines are:

for (int row = 0; row < 8; row++)
    for (int col = 0; col < 8; col++)
        // Do Something

For such a simple "double loop" iteration, there must be some way of either reducing the number of times these two lines appear, or making the code simpler.

Can anyone reduce the character count of this?

EDIT:

For more information,

because the code is repeated so often, I either want to reduce the character count or use an alternative to two for-loops.

the code is used as following (for examples):

for (int row = 0; row < 8; row++)
    for (int col = 0; col < 8; col++)
        setVal();   

for (int row = 0; row < 8; row++)
    for (int col = 0; col < 8; col++)
        getVal(); 

Author:ggle,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/27828082/improve-rowcol-iteration-efficiency-java
Paul Boddington :

I don't know what's wrong with the nested loops, but you can make this a bit shorter in java 8 using lambdas.\n\nWrite a general method representing the nested loops.\n\nprivate static void loops(BiConsumer<Integer, Integer> biConsumer) {\n for (int row = 0; row < 8; row++)\n for (int col = 0; col < 8; col++)\n biConsumer.accept(row, col);\n}\n\n\nYou can then call it like this:\n\nloops((row, col) -> System.out.println(\"The cell is (\" + row + \", \" + col + \")\"));\n\n\nIn general you can write it like this:\n\nloops((row, col) -> {\n // Put your code in here.\n});\n",
2015-01-07T21:00:45
JimW :

Assuming you want setVal() and getVal() to know about row and column you could do something like the following:\n\nvoid matrixExecute(MatrixExecutor executor) {\n for (int row = 0; row < 8; row++) {\n for (int col = 0; col < 8; col++) {\n executor.execute(col, row);\n }\n }\n}\nprivate interface MatrixExecutor {\n void execute(int col, int row);\n}\n\n\nTo use this implement inline:\n\nmatrixExecute(new MatrixExecutor() {\n @Override\n public void execute(int col, int row) {\n System.out.println(\"col:\" + col + \"row:\" + row);\n }\n });\n\n\nWhile this is still pretty wordy, when you move to Java 8 and the lamda expressions it's pretty nice:\n\nmatrixExecute((col,row) -> { System.out.println(\"col:\"+col+\"row:\"+row);});\n\n\nNote that will need to make sure you know about closures.",
2015-01-07T21:08:21
yy