Added in API level 24

Collectors

public final class Collectors
extends Object

java.lang.Object
   ↳ java.util.stream.Collectors


Implementations of Collector that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

The following are examples of using the predefined collectors to perform common mutable reduction tasks:

// Accumulate names into a List
 List list = people.stream()
   .map(Person::getName)
   .collect(Collectors.toList());

 // Accumulate names into a TreeSet
 Set set = people.stream()
   .map(Person::getName)
   .collect(Collectors.toCollection(TreeSet::new));

 // Convert elements to strings and concatenate them, separated by commas
 String joined = things.stream()
   .map(Object::toString)
   .collect(Collectors.joining(", "));

 // Compute sum of salaries of employee
 int total = employees.stream()
   .collect(Collectors.summingInt(Employee::getSalary));

 // Group employees by department
 Map> byDept = employees.stream()
   .collect(Collectors.groupingBy(Employee::getDepartment));

 // Compute sum of salaries by department
 Map totalByDept = employees.stream()
   .collect(Collectors.groupingBy(Employee::getDepartment,
                                  Collectors.summingInt(Employee::getSalary)));

 // Partition students into passing and failing
 Map> passingFailing = students.stream()
   .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

 

Summary

Public methods

static CollectorDouble> averagingDouble(ToDoubleFunction mapper)

Returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.

static CollectorDouble> averagingInt(ToIntFunction mapper)

Returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.

static CollectorDouble> averagingLong(ToLongFunction mapper)

Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.

static Collector collectingAndThen(Collector downstream, Function finisher)

Adapts a Collector to perform an additional finishing transformation.

static CollectorLong> counting()

Returns a Collector accepting elements of type T that counts the number of input elements.

static Collector filtering(Predicate predicate, Collector downstream)

Adapts a Collector to one accepting elements of the same type T by applying the predicate to each input element and only accumulating if the predicate returns true.

static Collector flatMapping(FunctionStream> mapper, Collector downstream)

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a flat mapping function to each input element before accumulation.

static Map> Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static CollectorMapList>> groupingBy(Function classifier)

Returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.

static CollectorMap> groupingBy(Function classifier, Collector downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static ConcurrentMap> Collector groupingByConcurrent(Function classifier, Supplier mapFactory, Collector downstream)

Returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static CollectorConcurrentMap> groupingByConcurrent(Function classifier, Collector downstream)

Returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

static CollectorConcurrentMapList>> groupingByConcurrent(Function classifier)

Returns a concurrent Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function.

static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

static Collector<CharSequence, ?, String> joining(CharSequence delimiter)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

static Collector<CharSequence, ?, String> joining()

Returns a Collector that concatenates the input elements into a String, in encounter order.

static Collector mapping(Function mapper, Collector downstream)

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a mapping function to each input element before accumulation.

static CollectorOptional> maxBy(Comparator comparator)

Returns a Collector that produces the maximal element according to a given Comparator, described as an Optional.

static CollectorOptional> minBy(Comparator comparator)

Returns a Collector that produces the minimal element according to a given Comparator, described as an Optional.

static CollectorMap<Boolean, D>> partitioningBy(Predicate predicate, Collector downstream)

Returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map whose values are the result of the downstream reduction.

static CollectorMap<BooleanList>> partitioningBy(Predicate predicate)

Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map>.

static CollectorOptional> reducing(BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator.

static Collector reducing(U identity, Function mapper, BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator.

static Collector reducing(T identity, BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

static CollectorDoubleSummaryStatistics> summarizingDouble(ToDoubleFunction mapper)

Returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

static CollectorIntSummaryStatistics> summarizingInt(ToIntFunction mapper)

Returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

static CollectorLongSummaryStatistics> summarizingLong(ToLongFunction mapper)

Returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.

static CollectorDouble> summingDouble(ToDoubleFunction mapper)

Returns a Collector that produces the sum of a double-valued function applied to the input elements.

static CollectorInteger> summingInt(ToIntFunction mapper)

Returns a Collector that produces the sum of an integer-valued function applied to the input elements.

static CollectorLong> summingLong(ToLongFunction mapper)

Returns a Collector that produces the sum of a long-valued function applied to the input elements.

static Collector teeing(Collector downstream1, Collector downstream2, BiFunction merger)

Returns a Collector that is a composite of two downstream collectors.

static Collection> Collector toCollection(Supplier collectionFactory)

Returns a Collector that accumulates the input elements into a new Collection, in encounter order.

static CollectorConcurrentMap> toConcurrentMap(Function keyMapper, Function valueMapper)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static ConcurrentMap> Collector toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapFactory)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorConcurrentMap> toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorList> toList()

Returns a Collector that accumulates the input elements into a new List.

static Map> Collector toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapFactory)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorMap> toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorMap> toMap(Function keyMapper, Function valueMapper)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorSet> toSet()

Returns a Collector that accumulates the input elements into a new Set.

static CollectorList> toUnmodifiableList()

Returns a Collector that accumulates the input elements into an unmodifiable List in encounter order.

static CollectorMap> toUnmodifiableMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

Returns a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorMap> toUnmodifiableMap(Function keyMapper, Function valueMapper)

Returns a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements.

static CollectorSet> toUnmodifiableSet()

Returns a Collector that accumulates the input elements into an unmodifiable Set.

Inherited methods

Public methods

averagingDouble

Added in API level 24
public static CollectorDouble> averagingDouble (ToDoubleFunction mapper)

Returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements. If no elements are present, the result is 0.

The average returned can vary depending upon the order in which values are recorded, due to accumulated rounding error in addition of values of differing magnitudes. Values sorted by increasing absolute magnitude tend to yield more accurate results. If any recorded value is a NaN or the sum is at any point a NaN then the average will be NaN.

Implementation Note:
  • The double format can represent all consecutive integers in the range -253 to 253. If the pipeline has more than 253 values, the divisor in the average computation will saturate at 253, leading to additional numerical errors.
Parameters
mapper ToDoubleFunction: a function extracting the property to be averaged
Returns
CollectorDouble> a Collector that produces the arithmetic mean of a derived property

averagingInt

Added in API level 24
public static CollectorDouble> averagingInt (ToIntFunction mapper)

Returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements. If no elements are present, the result is 0.

Parameters
mapper ToIntFunction: a function extracting the property to be averaged
Returns
CollectorDouble> a Collector that produces the arithmetic mean of a derived property

averagingLong

Added in API level 24
public static CollectorDouble> averagingLong (ToLongFunction mapper)

Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements. If no elements are present, the result is 0.

Parameters
mapper ToLongFunction: a function extracting the property to be averaged
Returns
CollectorDouble> a Collector that produces the arithmetic mean of a derived property

collectingAndThen

Added in API level 24
public static Collector collectingAndThen (Collector downstream, 
                Function finisher)

Adapts a Collector to perform an additional finishing transformation. For example, one could adapt the toList() collector to always produce an immutable list with:

List list = people.stream().collect(
   collectingAndThen(toList(),
                     Collections::unmodifiableList));
 
Parameters
downstream Collector: a collector
finisher Function: a function to be applied to the final result of the downstream collector
Returns
Collector a collector which performs the action of the downstream collector, followed by an additional finishing step

counting

Added in API level 24
public static CollectorLong> counting ()

Returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.

Implementation Requirements:
  • This produces a result equivalent to:
    reducing(0L, e -> 1L, Long::sum)
     
Returns
CollectorLong> a Collector that counts the input elements

filtering

Added in API level 33
public static Collector filtering (Predicate predicate, 
                Collector downstream)

Adapts a Collector to one accepting elements of the same type T by applying the predicate to each input element and only accumulating if the predicate returns true.

API Note:
  • The filtering() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy. For example, given a stream of Employee, to accumulate the employees in each department that have a salary above a certain threshold:
    Map> wellPaidEmployeesByDepartment
       = employees.stream().collect(
         groupingBy(Employee::getDepartment,
                    filtering(e -> e.getSalary() > 2000,
                              toSet())));
     
    A filtering collector differs from a stream's filter() operation. In this example, suppose there are no employees whose salary is above the threshold in some department. Using a filtering collector as shown above would result in a mapping from that department to an empty Set. If a stream filter() operation were done instead, there would be no mapping for that department at all.
Parameters
predicate Predicate: a predicate to be applied to the input elements
downstream Collector: a collector which will accept values that match the predicate
Returns
Collector a collector which applies the predicate to the input elements and provides matching elements to the downstream collector

flatMapping

Added in API level 33
public static Collector flatMapping (FunctionStream> mapper, 
                Collector downstream)

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a flat mapping function to each input element before accumulation. The flat mapping function maps an input element to a stream covering zero or more output elements that are then accumulated downstream. Each mapped stream is closed after its contents have been placed downstream. (If a mapped stream is null an empty stream is used, instead.)

API Note:
  • The flatMapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy. For example, given a stream of Order, to accumulate the set of line items for each customer:
    Map> itemsByCustomerName
       = orders.stream().collect(
         groupingBy(Order::getCustomerName,
                    flatMapping(order -> order.getLineItems().stream(),
                                toSet())));
     
Parameters
mapper Function: a function to be applied to the input elements, which returns a stream of results
downstream Collector: a collector which will receive the elements of the stream returned by mapper
Returns
Collector a collector which applies the mapping function to the input elements and provides the flat mapped results to the downstream collector

groupingBy

Added in API level 24
public static Collector groupingBy (Function classifier, 
                Supplier mapFactory, 
                Collector downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The Map produced by the Collector is created with the supplied factory function.

The classification function maps elements to some key type K. The downstream collector operates on elements of type T and produces a result of type D. The resulting collector produces a Map.

For example, to compute the set of last names of people in each city, where the city names are sorted:

Map> namesByCity
   = people.stream().collect(
     groupingBy(Person::getCity,
                TreeMap::new,
                mapping(Person::getLastName,
                        toSet())));
 
Implementation Note:
Parameters
classifier Function: a classifier function mapping input elements to keys
mapFactory Supplier: a supplier providing a new empty Map into which the results will be inserted
downstream Collector: a Collector implementing the downstream reduction
Returns
Collector a Collector implementing the cascaded group-by operation

groupingBy

Added in API level 24
public static CollectorMapList>> groupingBy (Function classifier)

Returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.

The classification function maps elements to some key type K. The collector produces a Map> whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are Lists containing the input elements which map to the associated key under the classification function.

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List objects returned.

Implementation Requirements:
  • This produces a result similar to:
    groupingBy(classifier, toList());
     
Implementation Note:
  • The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If preservation of the order in which elements appear in the resulting Map collector is not required, using groupingByConcurrent(java.util.function.Function) may offer better parallel performance.
Parameters
classifier Function: the classifier function mapping input elements to keys
Returns
CollectorMapList>> a Collector implementing the group-by operation

groupingBy

Added in API level 24
public static CollectorMap> groupingBy (Function classifier, 
                Collector downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

The classification function maps elements to some key type K. The downstream collector operates on elements of type T and produces a result of type D. The resulting collector produces a Map.

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

For example, to compute the set of last names of people in each city:

Map> namesByCity
   = people.stream().collect(
     groupingBy(Person::getCity,
                mapping(Person::getLastName,
                        toSet())));
 
Implementation Note:
  • The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If preservation of the order in which elements are presented to the downstream collector is not required, using groupingByConcurrent(java.util.function.Function, java.util.stream.Collector) may offer better parallel performance.
Parameters
classifier Function: a classifier function mapping input elements to keys
downstream Collector: a Collector implementing the downstream reduction
Returns
CollectorMap> a Collector implementing the cascaded group-by operation

groupingByConcurrent

Added in API level 24
public static Collector groupingByConcurrent (Function classifier, 
                Supplier mapFactory, 
                Collector downstream)

Returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The ConcurrentMap produced by the Collector is created with the supplied factory function.

This is a concurrent and unordered Collector.

The classification function maps elements to some key type K. The downstream collector operates on elements of type T and produces a result of type D. The resulting collector produces a ConcurrentMap.

For example, to compute the set of last names of people in each city, where the city names are sorted:

ConcurrentMap> namesByCity
   = people.stream().collect(
     groupingByConcurrent(Person::getCity,
                          ConcurrentSkipListMap::new,
                          mapping(Person::getLastName,
                                  toSet())));
 
Parameters
classifier Function: a classifier function mapping input elements to keys
mapFactory Supplier: a supplier providing a new empty ConcurrentMap into which the results will be inserted
downstream Collector: a Collector implementing the downstream reduction
Returns
Collector a concurrent, unordered Collector implementing the cascaded group-by operation

groupingByConcurrent

Added in API level 24
public static CollectorConcurrentMap> groupingByConcurrent (Function classifier, 
                Collector downstream)

Returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

This is a concurrent and unordered Collector.

The classification function maps elements to some key type K. The downstream collector operates on elements of type T and produces a result of type D. The resulting collector produces a ConcurrentMap.

There are no guarantees on the type, mutability, or serializability of the ConcurrentMap returned.

For example, to compute the set of last names of people in each city, where the city names are sorted:

ConcurrentMap> namesByCity
   = people.stream().collect(
     groupingByConcurrent(Person::getCity,
                          mapping(Person::getLastName,
                                  toSet())));
 
Parameters
classifier Function: a classifier function mapping input elements to keys
downstream Collector: a Collector implementing the downstream reduction
Returns
CollectorConcurrentMap> a concurrent, unordered Collector implementing the cascaded group-by operation

groupingByConcurrent

Added in API level 24
public static CollectorConcurrentMapList>> groupingByConcurrent (Function classifier)

Returns a concurrent Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function.

This is a concurrent and unordered Collector.

The classification function maps elements to some key type K. The collector produces a ConcurrentMap> whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are Lists containing the input elements which map to the associated key under the classification function.

There are no guarantees on the type, mutability, or serializability of the ConcurrentMap or List objects returned, or of the thread-safety of the List objects returned.

Implementation Requirements:
  • This produces a result similar to:
    groupingByConcurrent(classifier, toList());
     
Parameters
classifier Function: a classifier function mapping input elements to keys
Returns
CollectorConcurrentMapList>> a concurrent, unordered Collector implementing the group-by operation

joining

Added in API level 24
public static Collector<CharSequence, ?, String> joining (CharSequence delimiter, 
                CharSequence prefix, 
                CharSequence suffix)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

Parameters
delimiter CharSequence: the delimiter to be used between each element
prefix CharSequence: the sequence of characters to be used at the beginning of the joined result
suffix CharSequence: the sequence of characters to be used at the end of the joined result
Returns
Collector<CharSequence, ?, String> A Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order

joining

Added in API level 24
public static Collector<CharSequence, ?, String> joining (CharSequence delimiter)

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Parameters
delimiter CharSequence: the delimiter to be used between each element
Returns
Collector<CharSequence, ?, String> A Collector which concatenates CharSequence elements, separated by the specified delimiter, in encounter order

joining

Added in API level 24
public static Collector<CharSequence, ?, String> joining ()

Returns a Collector that concatenates the input elements into a String, in encounter order.

Returns
Collector<CharSequence, ?, String> a Collector that concatenates the input elements into a String, in encounter order

mapping

Added in API level 24
public static Collector mapping (Function mapper, 
                Collector downstream)

Adapts a Collector accepting elements of type U to one accepting elements of type T by applying a mapping function to each input element before accumulation.

API Note:
  • The mapping() collectors are most useful when used in a multi-level reduction, such as downstream of a groupingBy or partitioningBy. For example, given a stream of Person, to accumulate the set of last names in each city:
    Map> lastNamesByCity
       = people.stream().collect(
         groupingBy(Person::getCity,
                    mapping(Person::getLastName,
                            toSet())));
     
Parameters
mapper Function: a function to be applied to the input elements
downstream Collector: a collector which will accept mapped values
Returns
Collector a collector which applies the mapping function to the input elements and provides the mapped results to the downstream collector

maxBy

Added in API level 24
public static CollectorOptional> maxBy (Comparator comparator)

Returns a Collector that produces the maximal element according to a given Comparator, described as an Optional.

Implementation Requirements:
  • This produces a result equivalent to:
    reducing(BinaryOperator.maxBy(comparator))
     
Parameters
comparator Comparator: a Comparator for comparing elements
Returns
CollectorOptional> a Collector that produces the maximal value

minBy

Added in API level 24
public static CollectorOptional> minBy (Comparator comparator)

Returns a Collector that produces the minimal element according to a given Comparator, described as an Optional.

Implementation Requirements:
  • This produces a result equivalent to:
    reducing(BinaryOperator.minBy(comparator))
     
Parameters
comparator Comparator: a Comparator for comparing elements
Returns
CollectorOptional> a Collector that produces the minimal value

partitioningBy

Added in API level 24
public static CollectorMap<Boolean, D>> partitioningBy (Predicate predicate, 
                Collector downstream)

Returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map whose values are the result of the downstream reduction.

The returned Map always contains mappings for both false and true keys. There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

API Note:
  • If a partition has no elements, its value in the result Map will be obtained by calling the downstream collector's supplier function and then applying the finisher function.
Parameters
predicate Predicate: a predicate used for classifying input elements
downstream Collector: a Collector implementing the downstream reduction
Returns
CollectorMap<Boolean, D>> a Collector implementing the cascaded partitioning operation

partitioningBy

Added in API level 24
public static CollectorMap<BooleanList>> partitioningBy (Predicate predicate)

Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map>. The returned Map always contains mappings for both false and true keys. There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List returned.

API Note:
  • If a partition has no elements, its value in the result Map will be an empty List.
Parameters
predicate Predicate: a predicate used for classifying input elements
Returns
CollectorMap<BooleanList>> a Collector implementing the partitioning operation

reducing

Added in API level 24
public static CollectorOptional> reducing (BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator. The result is described as an Optional.

API Note:
  • The reducing() collectors are most useful when used in a multi-level reduction, downstream of groupingBy or partitioningBy. To perform a simple reduction on a stream, use Stream.reduce(BinaryOperator) instead.

    For example, given a stream of Person, to calculate tallest person in each city:

    Comparator byHeight = Comparator.comparing(Person::getHeight);
     Map> tallestByCity
       = people.stream().collect(
         groupingBy(Person::getCity,
                    reducing(BinaryOperator.maxBy(byHeight))));
     
Parameters
op BinaryOperator: a BinaryOperator used to reduce the input elements
Returns
CollectorOptional> a Collector which implements the reduction operation

reducing

Added in API level 24
public static Collector reducing (U identity, 
                Function mapper, 
                BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator. This is a generalization of reducing(java.lang.Object, java.util.function.BinaryOperator) which allows a transformation of the elements before reduction.

API Note:
  • The reducing() collectors are most useful when used in a multi-level reduction, downstream of groupingBy or partitioningBy. To perform a simple map-reduce on a stream, use Stream.map(Function) and Stream.reduce(Object, BinaryOperator) instead.

    For example, given a stream of Person, to calculate the longest last name of residents in each city:

    Comparator byLength = Comparator.comparing(String::length);
     Map longestLastNameByCity
       = people.stream().collect(
         groupingBy(Person::getCity,
                    reducing("",
                             Person::getLastName,
                             BinaryOperator.maxBy(byLength))));
     
Parameters
identity U: the identity value for the reduction (also, the value that is returned when there are no input elements)
mapper Function: a mapping function to apply to each input value
op BinaryOperator: a BinaryOperator used to reduce the mapped values
Returns
Collector a Collector implementing the map-reduce operation

reducing

Added in API level 24
public static Collector reducing (T identity, 
                BinaryOperator op)

Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

API Note:
  • The reducing() collectors are most useful when used in a multi-level reduction, downstream of groupingBy or partitioningBy. To perform a simple reduction on a stream, use Stream.reduce(Object, BinaryOperator)} instead.
Parameters
identity T: the identity value for the reduction (also, the value that is returned when there are no input elements)
op BinaryOperator: a BinaryOperator used to reduce the input elements
Returns
Collector a Collector which implements the reduction operation

summarizingDouble

Added in API level 24
public static CollectorDoubleSummaryStatistics> summarizingDouble (ToDoubleFunction mapper)

Returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

Parameters
mapper ToDoubleFunction: a mapping function to apply to each element
Returns
CollectorDoubleSummaryStatistics> a Collector implementing the summary-statistics reduction

summarizingInt

Added in API level 24
public static CollectorIntSummaryStatistics> summarizingInt (ToIntFunction mapper)

Returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

Parameters
mapper ToIntFunction: a mapping function to apply to each element
Returns
CollectorIntSummaryStatistics> a Collector implementing the summary-statistics reduction

summarizingLong

Added in API level 24
public static CollectorLongSummaryStatistics> summarizingLong (ToLongFunction mapper)

Returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.

Parameters
mapper ToLongFunction: the mapping function to apply to each element
Returns
CollectorLongSummaryStatistics> a Collector implementing the summary-statistics reduction

summingDouble

Added in API level 24
public static CollectorDouble> summingDouble (ToDoubleFunction mapper)

Returns a Collector that produces the sum of a double-valued function applied to the input elements. If no elements are present, the result is 0.

The sum returned can vary depending upon the order in which values are recorded, due to accumulated rounding error in addition of values of differing magnitudes. Values sorted by increasing absolute magnitude tend to yield more accurate results. If any recorded value is a NaN or the sum is at any point a NaN then the sum will be NaN.

Parameters
mapper ToDoubleFunction: a function extracting the property to be summed
Returns
CollectorDouble> a Collector that produces the sum of a derived property

summingInt

Added in API level 24
public static CollectorInteger> summingInt (ToIntFunction mapper)

Returns a Collector that produces the sum of an integer-valued function applied to the input elements. If no elements are present, the result is 0.

Parameters
mapper ToIntFunction: a function extracting the property to be summed
Returns
CollectorInteger> a Collector that produces the sum of a derived property

summingLong

Added in API level 24
public static CollectorLong> summingLong (ToLongFunction mapper)

Returns a Collector that produces the sum of a long-valued function applied to the input elements. If no elements are present, the result is 0.

Parameters
mapper ToLongFunction: a function extracting the property to be summed
Returns
CollectorLong> a Collector that produces the sum of a derived property

teeing

Added in API level 35
public static Collector teeing (Collector downstream1, 
                Collector downstream2, 
                BiFunction merger)

Returns a Collector that is a composite of two downstream collectors. Every element passed to the resulting collector is processed by both downstream collectors, then their results are merged using the specified merge function into the final result.

The resulting collector functions do the following:

  • supplier: creates a result container that contains result containers obtained by calling each collector's supplier
  • accumulator: calls each collector's accumulator with its result container and the input element
  • combiner: calls each collector's combiner with two result containers
  • finisher: calls each collector's finisher with its result container, then calls the supplied merger and returns its result.

The resulting collector is Collector.Characteristics.UNORDERED if both downstream collectors are unordered and Collector.Characteristics.CONCURRENT if both downstream collectors are concurrent.

Parameters
downstream1 Collector: the first downstream collector
downstream2 Collector: the second downstream collector
merger BiFunction: the function which merges two results into the single one
Returns
Collector a Collector which aggregates the results of two supplied collectors.

toCollection

Added in API level 24
public static Collector toCollection (Supplier collectionFactory)

Returns a Collector that accumulates the input elements into a new Collection, in encounter order. The Collection is created by the provided factory.

Parameters
collectionFactory Supplier: a supplier providing a new empty Collection into which the results will be inserted
Returns
Collector a Collector which collects all the input elements into a Collection, in encounter order

toConcurrentMap

Added in API level 24
public static CollectorConcurrentMap> toConcurrentMap (Function keyMapper, 
                Function valueMapper)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toConcurrentMap(java.util.function.Function, java.util.function.Function, java.util.function.BinaryOperator) instead.

There are no guarantees on the type, mutability, or serializability of the ConcurrentMap returned.

API Note:
  • It is common for either the key or the value to be the input elements. In this case, the utility method Function.identity() may be helpful. For example, the following produces a ConcurrentMap mapping students to their grade point average:
    ConcurrentMap studentToGPA
       = students.stream().collect(
         toConcurrentMap(Function.identity(),
                         student -> computeGPA(student)));
     
    And the following produces a ConcurrentMap mapping a unique identifier to students:
    ConcurrentMap studentIdToStudent
       = students.stream().collect(
         toConcurrentMap(Student::getId,
                         Function.identity()));
     

    This is a concurrent and unordered Collector.

Parameters
keyMapper Function: the mapping function to produce keys
valueMapper Function: the mapping function to produce values
Returns
CollectorConcurrentMap> a concurrent, unordered Collector which collects elements into a ConcurrentMap whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to the input elements

toConcurrentMap

Added in API level 24
public static Collector toConcurrentMap (Function keyMapper, 
                Function valueMapper, 
                BinaryOperator mergeFunction, 
                Supplier mapFactory)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function. The ConcurrentMap is created by a provided supplier function.

This is a concurrent and unordered Collector.

Parameters
keyMapper Function: a mapping function to produce keys
valueMapper Function: a mapping function to produce values
mergeFunction BinaryOperator: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
mapFactory Supplier: a supplier providing a new empty ConcurrentMap into which the results will be inserted
Returns
Collector a concurrent, unordered Collector which collects elements into a ConcurrentMap whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function

toConcurrentMap

Added in API level 24
public static CollectorConcurrentMap> toConcurrentMap (Function keyMapper, 
                Function valueMapper, 
                BinaryOperator mergeFunction)

Returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

There are no guarantees on the type, mutability, or serializability of the ConcurrentMap returned.

API Note:
  • There are multiple ways to deal with collisions between multiple elements mapping to the same key. The other forms of toConcurrentMap simply use a merge function that throws unconditionally, but you can easily write more flexible merge policies. For example, if you have a stream of Person, and you want to produce a "phone book" mapping name to address, but it is possible that two persons have the same name, you can do as follows to gracefully deal with these collisions, and produce a ConcurrentMap mapping names to a concatenated list of addresses:
    ConcurrentMap phoneBook
       = people.stream().collect(
         toConcurrentMap(Person::getName,
                         Person::getAddress,
                         (s, a) -> s + ", " + a));
     

    This is a concurrent and unordered Collector.

Parameters
keyMapper Function: a mapping function to produce keys
valueMapper Function: a mapping function to produce values
mergeFunction BinaryOperator: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
Returns
CollectorConcurrentMap> a concurrent, unordered Collector which collects elements into a ConcurrentMap whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function

toList

Added in API level 24
public static CollectorList> toList ()

Returns a Collector that accumulates the input elements into a new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(java.util.function.Supplier).

Returns
CollectorList> a Collector which collects all the input elements into a List, in encounter order

toMap

Added in API level 24
public static Collector toMap (Function keyMapper, 
                Function valueMapper, 
                BinaryOperator mergeFunction, 
                Supplier mapFactory)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function. The Map is created by a provided supplier function.

Implementation Note:
Parameters
keyMapper Function: a mapping function to produce keys
valueMapper Function: a mapping function to produce values
mergeFunction BinaryOperator: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
mapFactory Supplier: a supplier providing a new empty Map into which the results will be inserted
Returns
Collector a Collector which collects elements into a Map whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function

toMap

Added in API level 24
public static CollectorMap> toMap (Function keyMapper, 
                Function valueMapper, 
                BinaryOperator mergeFunction)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

API Note:
  • There are multiple ways to deal with collisions between multiple elements mapping to the same key. The other forms of toMap simply use a merge function that throws unconditionally, but you can easily write more flexible merge policies. For example, if you have a stream of Person, and you want to produce a "phone book" mapping name to address, but it is possible that two persons have the same name, you can do as follows to gracefully deal with these collisions, and produce a Map mapping names to a concatenated list of addresses:
    Map phoneBook
       = people.stream().collect(
         toMap(Person::getName,
               Person::getAddress,
               (s, a) -> s + ", " + a));
     
Implementation Note:
Parameters
keyMapper Function: a mapping function to produce keys
valueMapper Function: a mapping function to produce values
mergeFunction BinaryOperator: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
Returns
CollectorMap> a Collector which collects elements into a Map whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function

toMap

Added in API level 24
public static CollectorMap> toMap (Function keyMapper, 
                Function valueMapper)

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys might have duplicates, use toMap(java.util.function.Function, java.util.function.Function, java.util.function.BinaryOperator) instead.

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

API Note:
  • It is common for either the key or the value to be the input elements. In this case, the utility method Function.identity() may be helpful. For example, the following produces a Map mapping students to their grade point average:
    Map studentToGPA
       = students.stream().collect(
         toMap(Function.identity(),
               student -> computeGPA(student)));
     
    And the following produces a Map mapping a unique identifier to students:
    Map studentIdToStudent
       = students.stream().collect(
         toMap(Student::getId,
               Function.identity()));
     
Implementation Note:
  • The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If it is not required that results are inserted into the Map in encounter order, using toConcurrentMap(java.util.function.Function, java.util.function.Function) may offer better parallel performance.
Parameters
keyMapper Function: a mapping function to produce keys
valueMapper Function: a mapping function to produce values
Returns
CollectorMap> a Collector which collects elements into a Map whose keys and values are the result of applying mapping functions to the input elements

toSet

Added in API level 24
public static CollectorSet> toSet ()

Returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned; if more control over the returned Set is required, use toCollection(java.util.function.Supplier).

This is an unordered Collector.

Returns
CollectorSet> a Collector which collects all the input elements into a Set

toUnmodifiableList

Added in API level 33
public static CollectorList> toUnmodifiableList ()

Returns a Collector that accumulates the input elements into an unmodifiable List in encounter order. The returned Collector disallows null values and will throw NullPointerException if it is presented with a null value.

Returns
CollectorList> a Collector that accumulates the input elements into an unmodifiable List in encounter order

toUnmodifiableMap

Added in API level 33
public static CollectorMap> toUnmodifiableMap (Function keyMapper, 
                Function valueMapper, 
                BinaryOperator mergeFunction)

Returns a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

The returned Collector disallows null keys and values. If either mapping function returns null, NullPointerException will be thrown.

Parameters
keyMapper Function: a mapping function to produce keys, must be non-null
valueMapper Function: a mapping function to produce values, must be non-null
mergeFunction BinaryOperator: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction), must be non-null
Returns
CollectorMap> a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements
Throws
NullPointerException if the keyMapper, valueMapper, or mergeFunction is null

toUnmodifiableMap

Added in API level 33
public static CollectorMap> toUnmodifiableMap (Function keyMapper, 
                Function valueMapper)

Returns a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys might have duplicates, use toUnmodifiableMap(java.util.function.Function, java.util.function.Function, java.util.function.BinaryOperator) to handle merging of the values.

The returned Collector disallows null keys and values. If either mapping function returns null, NullPointerException will be thrown.

Parameters
keyMapper Function: a mapping function to produce keys, must be non-null
valueMapper Function: a mapping function to produce values, must be non-null
Returns
CollectorMap> a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements
Throws
NullPointerException if either keyMapper or valueMapper is null

toUnmodifiableSet

Added in API level 33
public static CollectorSet> toUnmodifiableSet ()

Returns a Collector that accumulates the input elements into an unmodifiable Set. The returned Collector disallows null values and will throw NullPointerException if it is presented with a null value. If the input contains duplicate elements, an arbitrary element of the duplicates is preserved.

This is an unordered Collector.

Returns
CollectorSet> a Collector that accumulates the input elements into an unmodifiable Set