Explain Codes LogoExplain Codes Logo

Java 8 forEach with index

java
index-management
foreach-pattern
java-streams
Alex KataevbyAlex Kataev·Feb 25, 2025
TLDR

Java 8 doesn't serve index handling in forEach on a silver platter, but you can do a little matchmaking with IntStream.range and your collection via a lambda. Here's a handy snippet:

IntStream.range(0, list.size()).forEach(idx -> System.out.println("Index " + idx + " : " + list.get(idx)));

IntStream.range pushes index numbers out of its hat, which you grab alongside your list elements in the lambda's body, giving you what forEach isn't ready to serve up.

Pattern party– Dance with indices in forEach

Index management: Array is the new 'in' thing

final int[] index = new int[]{0}; list.forEach(e -> { // Your operation here System.out.println("Elemento numero " + e + " at index " + index[0]++ + ". Bam!"); //Who knew indices could dance salsa? });

This pattern maneuvers around mutable index tracking while maintaining the black-tie elegance of forEach.

forEachOrdered: A waltz with order

Parallel streams are a wild party. To preserve the encounter order while iterating, play gentle music with forEachOrdered:

list.parallelStream().forEachOrdered(e -> { // Your well-ordered operations here });

This ensures a choreographed dance, regardless of the DJ's choice of thread.

Libraries: Your ultimate party planners

Libraries like Apache Commons Lang pump up the volume on Java's index functionality:

IterableUtils.forEach(list, (index, element) -> { // Dance with index and element });

These libraries add an abstraction layer to hide index management's messy room.

Battle royal: Traditional loops vs. Stream

Classic for loop: Oldie but a goodie

Offers straightforward index access:

for (int i = 0; i < list.size(); i++) { // i as the index, clear as mud! }

It's a hard-hitting champion in cases where index manipulation is integral.

Stream: Amazing grace with an Achilles' heel

Streams are highbrow, but lacks a built-in index support. If index access becomes the celebrity guest, the traditional loop gets the VIP pass.

Concurrency: Where forEach shines

With read-only operations on a concurrent collection, using a forEach pattern ensures you're on the safe lane:

list.parallelStream().forEach(element -> { // Concurrency-safe read operations });

Today's multi-threaded party demands a bouncer. And forEach is your guy!

Performance: For whom the bell tolls

Between streams and traditional loops, bets are high. The winner might be decided by the size of your data and how you parallelize:

// Parallel processing for potential performance pump-up list.parallelStream().forEach(element -> { // Your beefed-up operations here });

Choosing the fighter wisely is key or else it could sting like a bee!