How are lazy streams implemented in Java 8? -
i reading java 8, "streams api". wanted know how streams can lazy?
i believe streams added library , there no changes done language support laziness. also, shocked if tells me it's achieved through reflection.
why need reflection laziness? example, consider class:
class lazyseq<t> { private final list<t> list; private predicate<? super t> predicate; public lazyseq(list<t> input) { this.list = new arraylist<>(input); } //here store predicate, don't perform filtering //you return new lazyseq new state public lazyseq<t> filter(predicate<? super t> predicate) { this.predicate = predicate; return this; } public void foreach(consumer<? super t> consumer){ if(predicate == null) { list.foreach(consumer); } else { for(t elem : list) { if(predicate.test(elem)) { consumer.accept(elem); } } } } }
when call filter
on lazy seq, filtering not happen example:
lazyseq<integer> lazyseq = new lazyseq<>(arrays.aslist(1, 2, 3, 4)); lazyseq = lazyseq.filter(i -> i%2 == 0);
if see content of sequence after calling filter, you'll see it's 1, 2, 3, 4
. when calling terminal operation, such foreach
, filtering done before using consumer. example:
lazyseq.filter(i -> i%2 == 0).foreach(system.out::println);
will print 2 , 4.
this same principle stream
s. source, chain operations have certains properties. these operations either intermediate, returns lazy stream (such filter
or map
), or terminal (such foreach
). of these terminal operations short-circuiting (such findfirst
), might not traverse pipeline (you can think of return in loop returns index of value in array example).
when calling terminal operation, chain of operations start execute @ end expected result.
laziness can achieved storing new state on pipeline when intermediate op applied, , when call terminal op, go states one-by-one on data.
the stream api not implemented way (it's bit more complex) principle here.
Comments
Post a Comment