groupByKeys<T> function

Map<MultiKey, List<T>> groupByKeys<T>(
  1. Iterable<T> items,
  2. List<Object? Function(T)> keys
)

Groups items by applying every selector in keys, bucketing rows whose composite key is equal. Returns a map from MultiKey to the list of items in that bucket, in first-seen insertion order.

Example:

groupByKeys(rows, [(r) => r['country'], (r) => r['year']]);

Audited: 2026-06-12 11:26 EDT

Implementation

Map<MultiKey, List<T>> groupByKeys<T>(Iterable<T> items, List<Object? Function(T)> keys) {
  final Map<MultiKey, List<T>> out = <MultiKey, List<T>>{};
  for (final T item in items) {
    final MultiKey key = MultiKey(keys.map((Object? Function(T) f) => f(item)).toList());
    out.putIfAbsent(key, () => <T>[]).add(item);
  }
  return out;
}