eachCountTo method

Map<K, int> eachCountTo(
  1. Map<K, int> destination
)

Groups elements by key and counts the elements in each group to the given map.

If the destination already has a value for a given key, that value is used as an initial value.

final words = 'one two three four five six seven eight nine ten'.split(' ');
final frequenciesByFirstChar =
    words.groupingBy((value) => value[0]).eachCount();

print('Counting first letters:');
print(frequenciesByFirstChar); // {o=1, t=3, f=2, s=2, e=1, n=1}

final moreWords = 'eleven twelve'.split(' ');
final moreFrequencies = moreWords
    .groupingBy((value) => value[0])
    .eachCountTo(frequenciesByFirstChar);

print(moreFrequencies); // {o=1, t=4, f=2, s=2, e=2, n=1}

Implementation

Map<K, int> eachCountTo(Map<K, int> destination) {
  final count = eachCount();
  return {...destination, ...count}.map((key, _) {
    return MapEntry(key, (destination[key] ?? 0) + (count[key] ?? 0));
  });
}