Groovy Streamというのがあるようです。「Lazy Generator class for Groovy」とのこと。
- http://timyates.github.com/groovy-stream/
- http://blog.bloidonia.com/post/22117894718/groovy-stream-a-lazy-generator-class-for-groovy
サンプル。
@GrabResolver(name='bloidonia', root='https://raw.github.com/timyates/bloidonia-repo/master') @Grab('com.bloidonia:groovy-stream:0.5.1') import groovy.stream.* Stream s3 = Stream.from 1..10 map { it + x++ } filter { it % 2 } using x:0 assert s3.collect() == [ 1, 4, 7, 10, 13 ]
Groovy 2.0の拡張モジュールに対応しており、リストやマップや範囲にtoStream()メソッドが注入されます。
@GrabResolver(name='bloidonia', root='https://raw.github.com/timyates/bloidonia-repo/master') @Grab('com.bloidonia:groovy-stream:0.5.1') import groovy.stream.Stream Stream x = ("a".."z").toStream() filter {println it;it<="c" ?: STOP} using(idx:0) map {[it, idx++]} assert x.collect() == [["a", 0], ["b", 1], ["c", 2]]
なお、上記を実行すると、"c"までで「STOP」するので繰り返しを打ち切れます。
Streamという名称については、なんでも、Java 8のlambdaの仕様でもStreamというものが検討されているらしく、それでStreamという名前だそうです。
調べたところ、Generatorというのは違う気がする。yieldは無いし(できる?)。
リストやマップの宣言的な初期化に、List内包表記的に使えて便利そうではある。