aggregateTo<R> method

Map<K, R> aggregateTo<R>(
  1. Map<K, R> destination,
  2. AggregateOperation<T, K, R> operation
)

For each group the operation is applied to the elements of that group sequentially.

The previous accumulated value is passed and the current element. The result per group is stored in the given destination map.

The key for each element is provided by the [](T element) operator.

final numbers = [3, 4, 5, 6, 7, 8, 9];

final aggregated = numbers
    .groupingBy((value) => value % 3)
    .aggregateTo({}, (key, accumulator, element, first) {
  return first ? '$key:$element' : '$accumulator-$element';
});

print(aggregated.values); // (0:3-6-9, 1:4-7, 2:5-8)

If the destination map already has a value corresponding to a key, then the elements that are being aggregated for that key will never be considered as first.

Implementation

Map<K, R> aggregateTo<R>(
  Map<K, R> destination,
  AggregateOperation<T, K, R> operation,
) {
  final it = sourceIterator;
  while (it.moveNext()) {
    final key = this[it.current]!;
    destination[key] = operation(
      key,
      destination[key],
      it.current,
      destination[key] == null,
    );
  }
  return destination;
}