Interview: Design an iterator for a collection of collections

前端 未结 6 1084
Happy的楠姐
Happy的楠姐 2020-12-29 12:09

Design an iterator for a collection of collections in java. The iterator should hide the nesting, allowing you to iterate all of the elements belonging to all of the collect

6条回答
  •  感情败类
    2020-12-29 12:26

    Here is another implementation:

    import java.util.Iterator;
    import java.util.NoSuchElementException;
    
    import static java.util.Collections.emptyIterator;
    
    public class Multiterator implements Iterator {
        private Iterator> root;
        private Iterator current;
    
        public Multiterator(Iterator> root) {
            this.root = root;
            current = null;
        }
    
        @Override
        public boolean hasNext() {
            if (current == null || !current.hasNext()) {
                current = getNextNonNullOrEmpty(root);
            }
            return current.hasNext();
        }
    
        private Iterator getNextNonNullOrEmpty(Iterator> root) {
            while (root.hasNext()) {
                Iterator next = root.next();
                if (next != null && next.hasNext()) {
                    return next;
                }
            }
            return emptyIterator();
        }
    
        @Override
        public E next() {
            if (current == null) {
                throw new NoSuchElementException();
            }
            return current.next();
        }
    }
    

提交回复
热议问题