groupingBy<K> method

Grouping<T, K> groupingBy<K>(
  1. K keySelector(
    1. T value
    )
)

Group elements by a key.

It creates a Grouping using the specified keySelector to extract a key from each element.

It can then be used with one of its group-and-fold operations.

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}

Implementation

Grouping<T, K> groupingBy<K>(K Function(T value) keySelector) {
  return Grouping._construct(
    this,
    fold({}, (group, element) {
      (group[keySelector(element)] ??= []).add(element);
      return group;
    }),
  );
}