jjz
jjz

Reputation: 23

Stop an iterator at an index

I am trying to stop an iterator at a certain index.

Example, I start off with ABCDEF and if I type iterator(3), I only want it to return ABC and not the rest. Below is what I have tried doing.

if(stop>this.size() ){ 
   throw new IndexOutOfBoundsException(); 
}
Iterator<E> iterator = iterator();
int  i = 0 ; 

while (iterator.hasNext()) {
    if(i<stop){
        iterator.next();
        i++;
    }
    else{
        break;
    }
}

Upvotes: 2

Views: 1303

Answers (2)

Gatusko
Gatusko

Reputation: 2598

This is my way to do it. Because I think op suggest the stop is the end of the loop.

if(stop>this.size() ){
throw new IndexOutOfBoundsException();
}
else
{
Iterator<E> iterator = iterator();

for (int j = 0; j <stop ; j++) {
    if(iterator.hasNext()){
     // Todo
     }else {
         break;
     }
  }
}

Upvotes: 0

Chetan Joshi
Chetan Joshi

Reputation: 5711

You can do your stuff like below code with for loop:

if(stop>this.size() ){
throw new IndexOutOfBoundsException();
}
Iterator<E> iterator = iterator();
int  i = 0 ;

for (int j = 0; j <3 ; j++) {
if(iterator.hasNext()){
//do what you want here loop itrate only three times
}else {
        i=j;
         break;
  }
}

Upvotes: 1

Related Questions