Stream :-
- Stream is a new addtion to Collection API in Java8 for building complex operations on collections using functional approach.These are different from input and output streams
- Stream takes Collections ,Arrays or I/O operations as input build up internal sequence of elements and perform required operations on them and gives the final result
- No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations.
- Streams as said are functional in nature . Streams doesn't modify directly the collection/source its working it just produces the final result
- Laziness-seeking :- Many functions[filter,map etc] that are provided by stream perform lazy evaluation, Methods that build up a Stream recipe but donot force a new value to be generated at the end are referred to as lazy.
- Intermediate operations return a new stream which meets the condition of predicate passed, they are always lazily executed.Traversal of pipeline source will not be started until Terminal operation is called.
- Terminal operations are executed eagerly. all the intermediate operations are executed when they reach a terminal operation.
- In below example only filter is used on employees list, as this is a lazy function actual stream result did not build
Lazy operation. out put not printed |
Here count method is called which will build required Stream result . Methods that use the
stream recipe generated and produce a final result are called Eager methods
Eager operation count |
- Its easy to find a function Lazy or Eager. If a function returns a stream then its lazy,if it returns a value other than stream or void then its eager function
There are two variants of streams available in Java8
- Stream :- Returns a sequential stream
- ParllelStream :- Stream executes in parallel i.e Java runtime divides the stream into multiple sub streams . Aggregate operations iterate over and process the substream in parallel and then combine the result
No comments:
Post a Comment