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();
}
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();
}
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();
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With