เชื่อมต่อตัววนซ้ำใน Groovy

ให้ตัววนซ้ำสามคน

it1, it2, it3

ฉันจะคืนตัววนซ้ำหนึ่งตัวที่วนซ้ำมากกว่า 1 จากนั้นมากกว่า 2 และสุดท้าย 3 ได้อย่างไร

เอาเป็นว่า

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

ฉันต้องการที่จะมีตัววนซ้ำที่จะกลับมา

1
2
3
4
5
6

person Theodor    schedule 30.10.2013    source แหล่งที่มา
comment
IIRC ไม่มีสิ่งใดในตัว ฝรั่ง และ Commons Collections ทั้งคู่มีคลาสยูทิลิตี้สำหรับการทำเช่นนี้ หรือคุณสามารถเขียนของคุณเองในบรรทัด 10-ish ของรหัส   -  person Dave Newton    schedule 30.10.2013


คำตอบ (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 พูด คุณสามารถใช้ 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 ]

หรือคอลเลกชันทั่วไป

@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 ]
person tim_yates    schedule 30.10.2013