API Stream - RichardDanielOliva/java-learning-wiki GitHub Wiki
Stream is defined as a sequence of elements coming from a source that supports operations for processing its data:
- declaratively using lambda expressions.
- Enabling the possible chaining of several operations, thus achieving a code easy to read and with a clear objective.
- Sequentially or parallel (Fork/Join).
The structures that support this new API are in the package java.util.stream and especially, the interface java.util.stream.Stream defines a Stream.
This API allows us to perform operations on data collections using the filter/mapping/reduction model, in which the data to be processed is selected (filter), converted to another type of data (mapping) and at the end the desired result is obtained (reduction).
The following example allows us to visualize the three (3) parts that make up a Stream:
- Source of information → The list of transactions Zero or more intermediate operations → You can see the filter operation and the mapToInt operation, operations that will be explained later in this article.
- Terminal operation that produces a result or an effect on the data → The sum operation can be appreciated, which will be explained later in this article.
List of transactions = ...
int sum = transactions
.stream()
.filter(t -> t.getProvider().getCity().equals("Cali"))
.mapToInt(Transaction::getPrice)
.sum();