Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simplifying Nested Loops With Java 8 Lambdas

DZone's Guide to

Simplifying Nested Loops With Java 8 Lambdas

A great way to keep looping code out of your main logic in Java 8 apps.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

This is just a quick tip for everyone who 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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java 8 ,lambdas ,nested loops

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}