groupBy<K> method

Map<K, Iterable<E>> groupBy<K>(
  1. K keySelector(
    1. E element
    )
)

Groups elements of the original collection by the key returned by the given keySelector function applied to each element and returns a Map where each group key is associated with a Iterable of corresponding elements.

Implementation

Map<K, Iterable<E>> groupBy<K>(K Function(E element) keySelector) {
  final groups = <K, Iterable<E>>{};

  for (final element in this) {
    final key = keySelector(element);

    groups.putIfAbsent(
      key,
      () => where((element) => keySelector(element) == key),
    );
  }

  return groups;
}