Getting ready

As we mentioned in the previous recipe, there are two overloaded versions of the collect() terminal operation, which allow us to create a collection of the stream elements:

  • R collect(Supplier<R> supplier, BiConsumer<R,T> accumulator, BiConsumer<R,R> combiner): Produces the R result using the passed-in functions applied to the stream elements of the T type
  • R collect(Collector<T, A, R> collector): Produces the R result using the passed-in Collector object applied to the stream elements of the T type

These operations can be also used to create a Map object, and in this recipe, we are going to demonstrate how to do so.

In support of the second of the preceding versions of the collect() operation, the Collectors class provides ...

Get Java 11 Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.