Use Guava Iterators
Guava has a common utility classes for this proposes. The exact answer in this terms will be:
In this example there is some risk to encounter IndexOutOfBoundsException if position
supplied is advance iterator beyond its bounds.
@Test
public void getNthElement() {
List<String> alphabet = Arrays.asList("a", "b", "c", "d");
Iterator<String> iterator = alphabet.iterator();
int position = 3;
String forthElement = Iterators.get(iterator, 3);
assertEquals("d", forthElement);
}
The Iterators has a convenient overload for get(Iterator<T>, int)
method so you'll never get a IndexOutOfBoundsException.
@Test
public void getNthElementWithDefaultValue() {
List<String> alphabet = Arrays.asList("a", "b", "c", "d");
Iterator<String> iterator = alphabet.iterator();
int position = 10;
final String actual = Iterators.get(iterator, position, "default");
assertEquals("default", actual);
}
If its necessary to just skip or reach to specific position, but here comes the @Nikolas's mentioned case. Here you can easily get the NoSuchElementException
@Test
public void advance() {
List<String> alphabet = Arrays.asList("a", "b", "c", "d", "e", "f");
Iterator<String> iterator = alphabet.iterator();
// will return the number of skipped elements
int advance = Iterators.advance(iterator, 3);
assertEquals(3, advance);
assertEquals("d", iterator.next());
}
@Test(expected = NoSuchElementException.class)
public void advanceBeyond() {
List<String> alphabet = Arrays.asList("a", "b", "c");
Iterator<String> iterator = alphabet.iterator();
int advance = Iterators.advance(iterator, 3);
// throws the exception because we advanced iterator to end
iterator.next();
}
If you can't or don't want to depend on Guava
Here is the very simple (educational) implementation to reach iterator's position.
public static <T> T get(Iterator<T> iterator, int pos) {
if (pos < 0) {
throw new IllegalArgumentException("Position is negative!");
}
int i = 0;
while (i++ < pos) {
iterator.next();
}
return iterator.next();
}