April 17, 2016
Java String Array of Iterators
Problem
Given the Java method signature below. It receives an array of string iterators. The method should return a single string iterator that chains all iterators in order skipping null values
1 |
public static Iterator iterateStrings(List<Iterator> stringIterators) |
Solution
We wrap the array of iterators in a list that implements the iterable interface and override the hasNext, next and remove methods.
- hasNext: it makes sure the current iterator is not null if it is null then there is no next item so it returns false otherwise it uses the current iterator hasNext method. It is kind of nesting, the outer hasNext uses the inner hasNext
- next: this keeps looping as long as an individual iterator has elements. It checks for nulls as well and the moment there is no more elements in the current iterator it moves to the next iterator in the array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
public static class MyClass implements Iterable { //List of string iterators private List<Iterator> m_itrArr; //Construct list from a list of string iterators public MyClass(List<Iterator> itrArr) { this.m_itrArr = itrArr; } @Override public Iterator iterator() { Iterator it = new Iterator() { //Index of current string iterator private int itr_indx = 0; @Override public boolean hasNext() { //Make sure the current iterator is not null //This check is a requirement in this problem if (m_itrArr.get(itr_indx) != null) { //If the current iterator has next then //the chain iterator has next as well if (m_itrArr.get(itr_indx).hasNext()) { return true; } //Otherwise I just use the next iterator //in the list of iterators. I also need //to make sure that we stop at the last //iterator else { if (itr_indx < m_itrArr.size()-1) { return m_itrArr.get(itr_indx+1).hasNext(); } else { return false; } } } else { return false; } } @Override public String next() { //As long as the current iterator has //elements that are not null get these elements while (m_itrArr.get(itr_indx).hasNext()) { String str = m_itrArr.get(itr_indx).next(); //Make sure the current string is not null //This check is a requirement in this problem if (str != null) { return str; } else { return next(); } } //Move to the next iterator in the list itr_indx++; return next(); } @Override public void remove() { //do nothing } }; return it; } } public static Iterator iterateStrings(List<Iterator> stringIterators) { //Wrap the iterator array in our custom built list MyClass list = new MyClass(stringIterators); return list.iterator(); } |