Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 745
Dilshad Abduwali Avatar asked Sep 18 '13 12:09

Dilshad Abduwali


2 Answers

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;
}
like image 62
Peter Lawrey Avatar answered Oct 20 '22 00:10

Peter Lawrey


You can try something like this

    String valBefore=new String();
    boolean flag=false;
    for (String i:str){
         if(i.equals("valueBeforeTheExpectedValue")){
             valBefore=i;
             flag=true;
             continue;
         } if (flag){
             // Now you are getting expected value
             // while valBefore has previous value 
             flag=false;
        }
    }
like image 34
Ruchira Gayan Ranaweera Avatar answered Oct 20 '22 01:10

Ruchira Gayan Ranaweera