mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Sunday, 3 April, 2016

Simplifying nested loops with Java 8 Lambdas

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.

 

Comments

  • codeshite - Tuesday, 12 April, 2016

    So we've gone from 6 lines of code to 11, almost double... all for the purpose of hiding:

    for (int i = 0; i < values.length; i++) {
    for (int k = 0; k < values[i].length; k++) {

    With:

    loop(values, (i, k) -> {

    Sometimes you have to think, are you doing this because it makes code more readable/maintainable, or just because there's a cool new feature you want to use and blog about.

  • Michael Scharhag - Monday, 25 April, 2016

    Please note that it is not simply about lines of code (if you reuse the method multiple times you can even save lines of code).
    The key is that it hides the loop complexity and lowers the amount of possible bugs (of by one errors, etc.).

Leave a reply