I'm a beginner in Java and I have to recieve values from such thing as Iterator<Iterator<Integer>>. For example, we may have:
{{1, 2}, {3, 4}, {5, 6}}
The result of next() should be 1. If we try next() one more time - 2, then - 3, 4, etc. Like getting values from 1D array one by one, but from 2D array. We should not copy anything. So, I wrote some bad code below:
public class IteratorNext {
private Iterator<Iterator<Integer>> values = null;
private Iterator<Integer> current;
public IteratorNext(Iterator<Iterator<Integer>> iterator) {
this.values = iterator;
}
public int next() throws NoSuchElementException {
current = values.next();
if (!current.hasNext()) {
values.next();
}
if (!values.hasNext() && !current.hasNext()) {
throw new NoSuchElementException("Reached end");
}
return current.next();
}
}
That code is not correct, because result of next() is 1, then 3, then 5 and because of exception here. How to fix this?
java-8? There is a simpler way to do this then.