How do I access the next element in for each loop in Java?

Dilshad Abduwali picture Dilshad Abduwali · Sep 18, 2013 · Viewed 44.6k times · Source

I am using a for each loop to visit each element of an array of Strings and checking specific characteristics of those Strings. I need to access the next element in this loop if the current one has shown the character desired. So the current on is just an indicator for me that the next one is the one I need to grap and process. Is there any way to store the current one and process the right next one?

thanks

Answer

Peter Lawrey picture Peter Lawrey · Sep 18, 2013

You either need to use an indexed loop.

for(int i=0;i<strings.length-1;i++) {
    String curr = strings[i];
    String next = strings[i+1];
}

or you need to compare the current to the previous not the next.

String curr = null;
for(String next: strings) {
    if (curr != null) {
        // compare
    }
    curr = next;
}