4.6.  Use Collectors with streams, including the groupingBy and partitioningBy operation

[Note]

When you are done with a stream, you often just want to look at the results instead of reducing them to a value.

You can use Stream.collect(...) method. It takes three arguments:

  1. A supplier to make new instances of the target object, for example, a constructor for a hash set

  2. An accumulator that adds an element to the target, for example, an add method

  3. An combiner that merges two objects into one, such as addAll

There is a convenient Collector interface for these three functions, and a Collectors class with factory methods for common collectors. To collect a stream into a list or set, you can simply call:


List<String> result = stream.collect(Collectors.toList());

					

or


Set<String> result = stream.collect(Collectors.toSet());

					

or if you want to control which kind of set you get, use the following call instead:


TreeSet<String> result = stream.collect(Collectors.toCollection(TreeSet::new));

					

[Important]

java.util.stream.Collector is an interface.

java.util.stream.Collectors is a final class whose static methods return pre-defined Collector implementations.

Professional hosting         Exam 1Z0-817: Upgrade OCP Java 6, 7 & 8 to Java SE 11 Developer Quiz     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz