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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.