4.6.  Develop code that uses the Stream.collect() method and Collectors class methods, such as averagingDouble(), groupingBy(), joining(), and partitioningBy()

[Note]
  • blah

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());

					

[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         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz