"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Track Iteration Count in Java\'s For-Each Loop?

How to Track Iteration Count in Java\'s For-Each Loop?

Published on 2024-11-14
Browse:250

How to Track Iteration Count in Java\'s For-Each Loop?

Accessing Iteration Index in Java's For-Each Loop

In Java's for-each loop, accessing the current iteration count can prove to be a bit challenging. Unlike the traditional for loop (e.g., for (int i = 0; i

Is there a built-in way?

Unfortunately, there is no built-in way to access an iteration count directly with the for-each loop construct.

Alternative Approach: Counter Variable

The only way to keep track of iteration count in a for-each loop is to manually define a counter variable and increment it within the loop. For example:

int counter = 0;
for (String s: stringArray) {
  // Do something with s
  counter  ;
}

This approach allows you to keep track of the current iteration and use it for various purposes, such as displaying progress or limiting the number of iterations.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3