Is it possible to merge iterators in Java?

后端 未结 14 1871
自闭症患者
自闭症患者 2020-11-30 08:14

Is it possible to merge iterators in Java? I have two iterators and I want to combine/merge them so that I could iterate though their elements in one go (in same loop) rathe

14条回答
  •  猫巷女王i
    2020-11-30 09:09

    You could create your own implementation of the Iterator interface which iterates over the iterators:

    public class IteratorOfIterators implements Iterator {
        private final List iterators;
    
        public IteratorOfIterators(List iterators) {
            this.iterators = iterators;
        }
    
        public IteratorOfIterators(Iterator... iterators) {
            this.iterators = Arrays.asList(iterators);
        }
    
    
        public boolean hasNext() { /* implementation */ }
    
        public Object next() { /* implementation */ }
    
        public void remove() { /* implementation */ }
    }
    

    (I've not added generics to the Iterator for brevity.) The implementation is not too hard, but isn't the most trivial, you need to keep track of which Iterator you are currently iterating over, and calling next() you'll need to iterate as far as you can through the iterators until you find a hasNext() that returns true, or you may hit the end of the last iterator.

    I'm not aware of any implementation that already exists for this.

    Update:
    I've up-voted Andrew Duffy's answer - no need to re-invent the wheel. I really need to look into Guava in more depth.

    I've added another constructor for a variable number of arguments - almost getting off topic, as how the class is constructed here isn't really of interest, just the concept of how it works.

提交回复
热议问题