Domanda

If I have two iterables and I want to create a third iterable by lazily intersecting them. How can this be done in groovy. I can and have done this using guava before. 

È stato utile?

Soluzione

Assuming you mean intersect by "joining the elements together, one at a time", I wrote a package groovy-stream which can do this lazily:

@Grab( 'com.bloidonia:groovy-stream:0.8.1' )
import groovy.stream.*

Iterable a = [ 1, 2, 3 ]
Iterable b = [ 4, 5, 6 ]

Stream.from( a )
      .zip( b ) { x, y -> [ x, y ] }
      .each { println it }

Which will print:

[1, 4]
[2, 5]
[3, 6]

Edit:

You could of course roll your own:

Iterable a = [ 1, 2, 3 ]
Iterable b = [ 4, 5, 6 ]

Iterable zip = new LazyZipper( a:a, b:b, joiner:{ x, y -> [ x, y ] } )

for( r in zip ) {
    println r
}

class LazyZipper implements Iterable {
    Iterable a
    Iterable b
    Closure  joiner

    class LazyIterator implements Iterator {
        Iterator ia
        Iterator ib

        void remove() { throw new UnsupportedOperationException() }
        boolean hasNext() { ia.hasNext() && ib.hasNext() }
        Object next() { joiner( ia.next(), ib.next() ) }
    }

    Iterator iterator() {
        new LazyIterator( ia:a.iterator(), ib:b.iterator() )
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top