package debugging; import java.util.Iterator; import java.util.NoSuchElementException; public class StringMergingIterator implements Iterator { private Iterator first; private Iterator second; private boolean turnSwitch; public StringMergingIterator(Iterator first, Iterator second){ this.first = first; this.second = second; this.turnSwitch = true; } @Override public boolean hasNext() { return first.hasNext() || second.hasNext(); } @Override public String next() { if(! hasNext()){ throw new NoSuchElementException(); } String result = null; if(! first.hasNext()){ result = second.next(); // Switch which iterator to return from } else if(! second.hasNext()){ result = first.next(); } else { if(turnSwitch){ result = first.next(); turnSwitch = false; } else { // This block would execute after the previous with two ifs result = second.next(); turnSwitch = true; } } return result; } }