Terminal operations
The Terminal operations are the most important operations of a stream pipeline. It is easy to accomplish everything without a need for any other operations. We have used already the forEach(Consumer<T>)
Terminal operation to print each element. It does not return a value; thus, it is used for its side effects. But the Stream
interface has many more powerful Terminal operations that do return values. The central among them is a collect()
operation, which has two forms, R collect(Collector<T, A, R> collector)
and R collect(Supplier<R> supplier, BiConsumer<R, T> accumulator, BiConsumer<R, R> combiner)
. These allow us to compose practically any process that can be applied to a stream. The classic example is as follows:
List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
As you can see, it is implemented in a way...