Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

[
  [1,2],
  [3],
  [4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

public class Vector2D {

    Iterator<List<Integer>> listIter;
    Iterator<Integer> numberIter;

    public Vector2D(List<List<Integer>> vec2d) {
        listIter = vec2d.iterator();
    }

    public int next() {

        return numberIter.next();

    }

    public boolean hasNext() {

        while(numberIter == null || !numberIter.hasNext()){
            if(listIter != null && listIter.hasNext())
                numberIter = listIter.next().iterator();
            else return false;
        }

        return true;
    }
}

results matching ""

    No results matching ""