Stream API
Stream API
One of the major new features in Java 8 is the introduction of the stream
functionality – java.util.stream – which contains classes for processing sequences of
elements.
The central API class is the Stream<T>. The following section will demonstrate how
streams can be created using the existing data-provider sources.
A stream is not a data structure instead it takes input from the Collections,
Arrays or I/O channels.
Streams don’t change the original data structure, they only provide the result
as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a
result, hence various intermediate operations can be pipelined. Terminal
operations mark the end of the stream and return the result.
Intermediate operations return another Stream which allows you to call multiple
operations in a form of a query. Intermediate operations do not get executed until a
terminal operation is invoked as there is a possibility they could be processed
together when a terminal operation is executed.
Intermediate Operations:
(i) filter: The filter method is used to select elements as per the Predicate
passed as argument.
(ii) map: The map method is used to map the items in the collection to other
objects according to the Predicate passed as argument.
(iii) sorted: The sorted method is used to sort the stream.
Terminal Operations:
(i) collect: The collect method is used to return the result of the intermediate
operations performed on the stream.
(ii) forEach: The forEach method is used to iterate through every element of
the stream.
(iii) reduce: The reduce method is used to reduce the elements of a stream to
a single value.
Stream Creation
There are many ways to create a stream instance of different sources. Once created,
the instance will not modify its source, therefore allowing the creation of multiple
instances from a single source.
(i) Empty Stream: The empty() method should be used in case of a creation of
an empty stream
(ii) Stream of Collection: Stream can also be created of any type of Collection
(Collection, List, Set)
Coding Examples: