Collectors and Statistics
Explore how to utilize Java 8 collectors to gather stream results into collections or strings. Understand how to compute statistics such as average, maximum, minimum, and count using summarizing collectors to analyze data efficiently in Java streams.
We'll cover the following...
We'll cover the following...
Introduction to collectors
Since streams are lazily evaluated and support parallel execution, we need a special way to combine results. For this, we use a Collector.
A Collector represents a way to combine the elements of a Stream into one result. It consists of three things:
- A
supplierof an initial value. - An
accumulatorwhich adds to the initial value. - A
combinerwhich combines two results into one.
There are two ways to do this: collect(supplier,accumulator,combiner) or collect(Collector) (types left off for brevity).
Luckily, Java 8 comes with several built-in ...