在Groovy中连接迭代器

时间:2013-10-30 13:39:31

标签: groovy iterator

给出三个迭代器

it1, it2, it3

我怎样才能返回迭代it1的一个迭代器,然后返回it2并持续it3?

让我们说

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

我想要一个将返回的迭代器

1
2
3
4
5
6

1 个答案:

答案 0 :(得分:1)

我在Groovy中没有这样的迭代器,但你可以编写自己的迭代器:

class SequentialIterator<T> implements Iterator<T> {
    List iterators
    int index = 0
    boolean done = false
    T next

    SequentialIterator( Iterator<T> ...iterators ) {
        this.iterators = iterators
        loadNext()
    }

    private void loadNext() {
        while( index < iterators.size() ) {
            if( iterators[ index ].hasNext() ) {
                next = iterators[ index ].next()
                break
            }
            else {
                index++
            }
        }
        if( index >= iterators.size() ) {
            done = true
        }
    }

    void remove() {
        throw UnsupportedOperationException()
    }

    boolean hasNext() {
        !done
    }

    T next() {
        if( done ) {
            throw new NoSuchElementException()
        }
        T ret = next
        loadNext()
        ret
    }
}

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert new SequentialIterator( it1, it2, it3 ).collect() == [ 1, 2, 3, 4, 5, 6 ]

或者,如果您感到贪婪(并且需要同时加载所有数据),您可以依次从迭代器中收集值:

[ it1, it2, it3 ].collectMany { it.collect() }

或者作为Dave Newton says,您可以使用Guava:

@Grab( 'com.google.guava:guava:15.0' )
import com.google.common.collect.Iterators

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert Iterators.concat( it1, it2, it3 ).collect() == [ 1, 2, 3, 4, 5, 6 ]

or commons-collections;

@Grab( 'commons-collections:commons-collections:3.2.1' )
import org.apache.commons.collections.iterators.IteratorChain

def it1 = [1, 2].iterator()
def it2 = [3, 4].iterator()
def it3 = [5, 6].iterator()

assert new IteratorChain( [ it1, it2, it3 ] ).collect() == [ 1, 2, 3, 4, 5, 6 ]