# Two approaches: Queue and iterators only

• Using Queue :

public class Vector2D implements Iterator<Integer> {

private Queue<Iterator<Integer>> iterators;

public Vector2D(List<List<Integer>> vector2d) {
vector2d.forEach(vector -> {
if (!vector.isEmpty()) {
iterators.offer(vector.iterator());
}
});
}

@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException("Empty iterator");
}

Iterator<Integer> current = iterators.peek();
int result = current.next();
if (!current.hasNext()) {
iterators.poll();
}

return result;
}

@Override
public boolean hasNext() {
return !iterators.isEmpty();
}
}

Using iterators only :

public class Vector2D implements Iterator<Integer> {

private final Iterator<Iterator<Integer>> nestedIterators;
private Iterator<Integer> current;

public Vector2D(final List<List<Integer>> vector2d) {
List<Iterator<Integer>> iterators = new ArrayList<>();
vector2d.forEach(vector -> {
if (!vector.isEmpty()) {
}
});
nestedIterators = iterators.iterator();
current = null;
}

@Override
public boolean hasNext() {
return nestedIterators.hasNext() || current != null;
}

@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException("Empty iterator");
}

if (current == null) {
current = nestedIterators.next();
}

int result = current.next();
if (!current.hasNext()) {
current = null;
}

return result;
}
}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.