Search⌘ K
AI Features

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.

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 supplier of an initial value.
  • An accumulator which adds to the initial value.
  • A combiner which 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 ...