Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling next() twice in Iterator throws a NoSuchElementException

I'm retrieving several values from a sequence, but need to do so twice for a separate set of values coming from the same sequence. If I call one or the other, everything comes back to me correctly, but calling next() twice results in a NoSuchElementException. After reading about this online, I've gathered that after calling next() once, any other time after that calling it again will basically return the iterator false. How do you get two separate sets of data from the same Collection?

while (ai.hasNext()) {
   String ao = ai.next().getImageURL(ImageSize.MEGA);
   String an= ai.next().getName();
}
like image 530
adneal Avatar asked Dec 27 '22 05:12

adneal


2 Answers

You can store next() as a temporary variable. Replace Object in the following code with the datatype you are iterating through.

while(ai.hasNext()){
    Object temp = ai.next();
    String ao = temp.getImageUrl(ImageSize.MEGA);
    String an = temp.getName();

}

like image 186
Nigel Avatar answered Dec 29 '22 19:12

Nigel


If you are not sure your list has an even number of elements, you just need to add if (ai.hasNext()) before your 2nd call to next().

while (ai.hasNext()) {
   String ao = ai.next().getImageURL(ImageSize.MEGA);
   if (ai.hasNext())) {
      String an= ai.next().getName();
      ...
   }
}
like image 29
Bruno Silva Avatar answered Dec 29 '22 18:12

Bruno Silva