group<GK> method

Map<GK, List<E>> group<GK>(
  1. GK groupKeyProvider(
    1. E item
    )
)

Groups items in this iterable by keys provided by groupKeyProvider.

Returns a map where each key maps to a list of items with that key. Returns an empty map if this iterable is null.

Example:

List<String>? words = ['apple', 'apricot', 'banana', 'blueberry'];
Map<String, List<String>> grouped = words.group((w) => w[0]); // {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry']}

Implementation

Map<GK, List<E>> group<GK>(GK Function(E item) groupKeyProvider) {
  Map<GK, List<E>> map = {};

  if (this == null) {
    return map;
  }

  for (var item in this!) {
    GK key = groupKeyProvider(item);
    map.putIfAbsent(key, () => []).add(item);
  }

  return map;
}