package oving5.debugging; import java.util.Iterator; import java.util.NoSuchElementException; public class StringMergingIterator implements Iterator { private final Iterator first; private final Iterator second; private boolean turnSwitch = true; public StringMergingIterator(Iterator first, Iterator second) { this.first = first; this.second = second; } @Override public boolean hasNext() { return this.first.hasNext() || this.second.hasNext(); } @Override public String next() { if (!this.hasNext()) { throw new NoSuchElementException(); } String result = null; if (!this.first.hasNext()) { result = this.first.next(); } else if (!this.second.hasNext()) { result = this.second.next(); } else { if (this.turnSwitch) { result = this.first.next(); this.turnSwitch = false; } if (!this.turnSwitch) { result = this.second.next(); this.turnSwitch = true; } } return result; } }