I am reading Java 8, specifically the \"Streams API\". I wanted to know how streams can be lazy?
I believe streams are just added as a library and there are no chang
No reflection or proxies. Reflection and proxies come with a performance cost that should be avoided unless there isn't an alternative and performance is number one in Java
.
What makes laziness possible is the functional style of doing things. Basically a stream
starts with a source(ex: List), number of intermediate operations (ex: filters, map..) , and a terminal operation (ex: count, sum, etc..).
Intermediate steps execute lazily because you pass functions (lambdas) that get chained in the pipeline to be executed at the terminal step.
ex: filter(Predicate super T>)
filter
in this example expects a function that tells us whether an object in the stream meets some criteria or not.
A lot of features that come from Java 7 have been used to make this efficient. Ex: invoke dynamic for executing lambdas rather than proxies or anonymous inner classes and ForkJoin
pools for parallel execution.
If you are interested in Java 8 internals,then you have to watch this talk given by the expert in the field Brian Goetz, it's on Youtube.