This is just a quick tip for everyone who often has to work with multi dimensional arrays in Java 8 (or newer).
In this case you might often end with code similar to this:
float[][] values = ...
for (int i = 0; i < values.length; i++) {
for (int k = 0; k < values[i].length; k++) {
float value = values[i][k];
// do something with i, k and value
}
}If you are lucky you can replace the loops with for-each loops. However, often the indices are required for computations inside the loop.
In such a case you can come up with a simple utility method that looks like this:
private void loop(float[][] values, BiConsumer<Integer, Integer> consumer) {
for (int i = 0; i < values.length; i++) {
for (int k = 0; k < values[i].length; k++) {
consumer.accept(i, k);
}
}
}We can now loop over array indices like this:
float[][] values = ...
loop(values, (i, k) -> {
float value = values[i][k];
// do something with i, k and value
});This way you can keep the looping code out of your main logic.
Of course you should change the shown loop() method so it fits your personal needs.
| Reference: | Simplifying nested loops with Java 8 Lambdas from our JCG partner Michael Scharhag at the mscharhag, Programming and Stuff blog. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
👁 Photo of Michael Scharhag
Michael ScharhagApril 4th, 2016Last Updated: April 4th, 2016
Michael ScharhagApril 4th, 2016Last Updated: April 4th, 2016
1 382 1 minute read

This site uses Akismet to reduce spam. Learn how your comment data is processed.
Hi Michael,
Thank you for this article. Is it possible to ask you an advice regarding nested for loop with java 8. Thank you very much. Jade