Streams Flashcards
To Learn Java 8 Streams API
What is a Stream
Stream provides manipulation of Java collections in a declarative way. Think stream is like a fancy iterator over collection.
what exactly is a stream?
“a sequence of elements from a
source that supports data-processing operations.”
Pipelining in stream?
Many stream operations return a stream themselves, allowing operations to be chained to form a larger pipeline.This enables certain optimizations
that we explain , such as laziness and short-circuiting.
How many times stream can be traversed?
Note that, similarly to iterators, a stream can be traversed only once. it will throw java.lang.IllegalStateException: stream has already been operated upon or closed.
Stream operations Categories?
The streams interface in java.util.stream.Stream defines many operations. They can be classified into two categories. Stream operations that can be connected are called intermediate operations, and operations
that close a stream are called terminal operations.
What are Intermediate operations?
Intermediate operations such as filter or sorted return another stream as the return type. This allows the operations to be connected to form a query. What’s important is that intermediate operations don’t perform any processing until a terminal operation is invoked on the stream pipeline—they’re lazy. This is because intermediate operations can usually be merged and processed into a single pass by the terminal operation.
What are Terminal operations?
Terminal operations produce result from a stream pipeline.
a result is any non stream value such as a List, an Integer , or even a void.
In the stream pipeline that follows, can you identify the intermediate and terminal
operations?
long count = menu.stream() .filter(dish -> dish.getCalories() > 300) .distinct() .limit(3) .count();
The last operation in the stream pipeline count returns a long, which is a non-stream
value. It’s therefore a terminal operation. All previous operations, filter, distinct,
limit, are connected and return a stream. They are therefore intermediate operations.
Summary
A stream is a sequence of elements from a source that supports data-processing
operations.
Streams make use of internal iteration: the iteration is abstracted away through
operations such as filter, map, and sorted.
There are two types of stream operations: intermediate and terminal operations.
Intermediate operations such as filter and map return a stream and can be
chained together. They’re used to set up a pipeline of operations but don’t produce
any result.
Terminal operations such as forEach and count return a non-stream value and
process a stream pipeline to return a result.
The elements of a stream are computed on demand (“lazily”).