groupBy<K> method

Map<K, List<T>> groupBy<K>(
  1. K keyFunction(
    1. T
    )
)

Groups the elements in the iterable according to the keyFunction. Returns a map where each key corresponds to a list of elements that share that key.

Example:

var list = ['a', 'ab', 'b'];
var result = list.groupBy((s) => s.length); // {1: ['a', 'b'], 2: ['ab']}

Implementation

Map<K, List<T>> groupBy<K>(K Function(T) keyFunction) {
  return fold(<K, List<T>>{}, (Map<K, List<T>> map, T element) {
    final K key = keyFunction(element);
    map.putIfAbsent(key, () => []).add(element);
    return map;
  });
}