Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current index of a for each loop iterating an ArrayList

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.

like image 593
Renaud is Not Bill Gates Avatar asked Jan 07 '14 00:01

Renaud is Not Bill Gates


People also ask

How do you find the index of an ArrayList?

The index of a particular element in an ArrayList can be obtained by using the method java. util. ArrayList. indexOf().

Can you use a For Each loop on an ArrayList?

We can use the Java for-each loop to iterate through each element of the arraylist.

How do you find an index forEach?

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);

Is there a way to access an iteration counter in Java for each loop?

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.


1 Answers

Just use a traditional for loop:

for (int i = 0; i < yourArrayList.size(); i ++) {     // i is the index     // yourArrayList.get(i) is the element } 
like image 51
tckmn Avatar answered Sep 21 '22 21:09

tckmn