Java Reference
In-Depth Information
We've now covered all the collectors that can be created using the static factory methods of the
Collectors class, showing practical examples of how they work. Table 6.1 brings them all together,
with the type they return when applied to a Stream<T> and a practical example of their use on a
Stream<Dish> named menuStream.
Table 6.1. The static factory methods of the Collectors class
Factory
method
Returned type
Used to
toList
List<T>
Gather all the stream's items in a List.
Example use: List<Dish> dishes = menuStream.collect(toList());
toSet
Set<T>
Gather all the stream's items in a Set, eliminating
duplicates.
Example use: Set<Dish> dishes = menuStream.collect(toSet());
toCollection
Collection<T>
Gather all the stream's items in the collection created
by the provided supplier.
Example use: Collection<Dish> dishes = menuStream.collect(toCollection(), ArrayList::new);
counting
Long
Count the number of items in the stream.
Example use: long howManyDishes = menuStream.collect(counting());
summingInt
Integer
Sum the values of an Integer property of the items in
the stream.
Example use: int totalCalories = menuStream.collect(summingInt(Dish::getCalories));
averagingInt
Double
Calculate the average value of an Integer property of
the items in the stream.
Example use: double avgCalories = menuStream.collect(averagingInt(Dish::getCalories));
summarizingInt
IntSummary-Statistics
Collect statistics regarding an Integer property of the
items in the stream, such as the maximum, minimum,
 
Search WWH ::




Custom Search