Is it possible to merge iterators in Java?

后端 未结 14 1867
自闭症患者
自闭症患者 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条回答
  •  青春惊慌失措
    2020-11-30 08:54

    I haven't written Java code in a while, and this got me curious to whether I've still "got it".

    First try:

    import java.util.Iterator;
    import java.util.Arrays; /* For sample code */
    
    public class IteratorIterator implements Iterator {
        private final Iterator is[];
        private int current;
    
        public IteratorIterator(Iterator... iterators)
        {
                is = iterators;
                current = 0;
        }
    
        public boolean hasNext() {
                while ( current < is.length && !is[current].hasNext() )
                        current++;
    
                return current < is.length;
        }
    
        public T next() {
                while ( current < is.length && !is[current].hasNext() )
                        current++;
    
                return is[current].next();
        }
    
        public void remove() { /* not implemented */ }
    
        /* Sample use */
        public static void main(String... args)
        {
                Iterator a = Arrays.asList(1,2,3,4).iterator();
                Iterator b = Arrays.asList(10,11,12).iterator();
                Iterator c = Arrays.asList(99, 98, 97).iterator();
    
                Iterator ii = new IteratorIterator(a,b,c);
    
                while ( ii.hasNext() )
                        System.out.println(ii.next());
        }
    }
    

    You could of course use more Collection classes rather than a pure array + index counter, but this actually feels a bit cleaner than the alternative. Or am I just biased from writing mostly C these days?

    Anyway, there you go. The answer to you question is "yes, probably".

提交回复
热议问题