I'm iterating an ArrayList
using the for each loop, but I don't know how to get the current index where the loop is.
I did Google it, but I couldn't find anything helpful.
Please, if someone could tell me how to get the current index, I'll be grateful.
The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().
We can use the Java for-each loop to iterate through each element of the arraylist.
A callback function is a simple function that defines the operation to be performed on a single element, and the forEach() method makes sure it will be performed on each element of an array. The forEach() method has a pretty straightforward syntax: forEach(callback(currentElement, index, arr), thisValue);
Adding a Counter to forEach with Stream Let's try to convert that into an operation that includes the counter. This function returns a new lambda. That lambda uses the AtomicInteger object to keep track of the counter during iteration. The getAndIncrement function is called every time there's a new item.
Just use a traditional for loop:
for (int i = 0; i < yourArrayList.size(); i ++) { // i is the index // yourArrayList.get(i) is the element }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With