Class collectors

The java.util.stream.Collectors class provides more than 40 methods that create Collector objects. We are going to demonstrate only the simplest and  most popular ones:

  • Collector<T,?,List<T>> toList(): Creates a collector that collects the stream elements into a List object.
  • Collector<T,?,Set<T>> toSet(): Creates a collector that collects the stream elements into a Set object.
  • Collector<T,?,Map<K,U>> toMap (Function<T,K> keyMapper, Function<T,U> valueMapper): Creates a collector that collects the stream elements into a Map object.
  • Collector<T,?,C> toCollection (Supplier<C> collectionFactory): Creates a collector that collects the stream elements into a Collection object of the type specified by the collection factory.

Get Introduction to Programming 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.