This tutorial is on java 8 streams API. Here we will be discussing about what is stream, different ways to obtain a stream and also about different stream operations with examples.
Stream can be defined as a sequence of elements or objects from any java collection supporting sequential and parallel aggregate operations. Java 8 streams does not require any storage. It simply streams any collection of elements, process the elements in parallel and again collects those resulting elements and returns a collection out of it.
Streams differ from collections in several ways:
A stream is not a data structure that stores elements; instead, it conveys elements from a source
An operation on a stream produces a result, but does not modify its source.
Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily.
The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.
Streams can be obtained in a number of ways.
From a Collection via the stream() and parallelStream() methods. Following is an example
From an array via Arrays.stream(Object). Following is an example:
Stream operations are divided into intermediate and terminal operations.A stream pipeline may have zero or more intermediate operations such as
Stream.map but only one terminal operation such as
Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as
filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
filter() - It is an intermediate operator and hence it requires a terminal operator like
count() to process it.Below is an example that filters numbers more than 100.
map() - This method is used to map elements of a stream to another. Following is an example which will print the small alphabets to upper case as output.
sorted() - It is an intermediate operator that sorts the elements in ascending order.
It performs reduction operation that takes a sequence of input elements and combines them into a single summary result such as finding the sum or maximum of a set of numbers, or accumulating elements into a list.
output - 1250
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
©2017, DevGlan. All Rights Reserved.
Contact us: email@example.com