Rakeeb Rajbhandari
Rakeeb Rajbhandari

Reputation: 5063

iteration progress detection Java

I wanted to check if the iteration I was executing was in its final execution:

for(String t: token)

How can I achieve this in the following case ? Here token is a String[] array

Upvotes: 0

Views: 248

Answers (6)

BjornArnelid
BjornArnelid

Reputation: 151

Just providing another way to do this using equals.

for(String t: token) {
  if(t.equals(token[token.length-1])) {
    // Do stuff
  }
}

Upvotes: 0

Tom Jonckheere
Tom Jonckheere

Reputation: 1648

Can't you use while?

int i = 0;
while(i < token.length)
{
    //check for last element
     if(i==token.length-1){

      }
}

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

If it is Iterable you can walk the iterator yourself:

List<String> token = Arrays.asList("First","Next","Last");
// Old way
for ( String t : token) {
  System.out.println(t);
}
// Using iterator.
for ( Iterator<String> i = token.iterator(); i.hasNext();) {
  String s = i.next();
  System.out.println((i.hasNext()?"":"*")+s);
}

or you could walk one step behind:

// One step behind.
String s = null;
for ( String t : token) {
  if ( s != null ) {
    System.out.println(s);
  }
  s = t;
}
if ( s != null ) {
  System.out.println("*"+s);
}

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

This will work for you

  int counter=0;
  for(String t: token){
        counter++;
        if(counter==token.length-1)){

        }

    }

But if you need focused on indexes you can use just a for-loop

   for(int i=0;i<token.length;i++){
       if(i==token.length-1){

        }
   }

Upvotes: 1

kai
kai

Reputation: 6887

You can do it like this:

      int counter = 0;
      for(String t: token) {
          counter++;
          if(counter==token.length-1) {
              //final iteration
          }
      }

Upvotes: 2

Mena
Mena

Reputation: 48404

With fast enumeration, you cannot retrieve the iteration's index.

However you can always use a counter that increments within your fast-enumeration loop, and act when its value is equal to the Collection or array's size minus 1.

Here's an example.

List<String> test = new ArrayList<String>();
// TODO populate
// outside counter
int counter = 0;
for (String s: test) {
    // TODO something
    // checking counter vs collection size: last element
    if (counter == test.size() - 1) {
        // TODO something
    }
    counter++;
}

However, a standard for loop would be most recommended instead:

for (int i = 0; i < test.size(); i++) {
    // checking counter vs collection size: last element
    if (i == test.size() - 1) {
        // TODO something
    }
}

Upvotes: 1

Related Questions