groupByAndMap<K, V> method

Map<K, List<V>> groupByAndMap<K, V>(
  1. K keySelector(
    1. T item
    ),
  2. V valueSelector(
    1. T item
    )
)

Groups elements of this iterable into a Map using keySelector, and applies valueSelector to each element before storing it.

Similar to Java's Collectors.groupingBy(..., Collectors.mapping(...)).

Example:

class Interest {
  final String name;
  final String category;
  Interest(this.name, this.category);
}

final interests = [
  Interest('Football', 'Sports'),
  Interest('Chess', 'Board Games'),
  Interest('Basketball', 'Sports'),
];

final groupedNames = interests.groupByAndMap(
  (i) => i.category,
  (i) => i.name,
);

print(groupedNames['Sports']); // [Football, Basketball]

Implementation

Map<K, List<V>> groupByAndMap<K, V>(K Function(T item) keySelector, V Function(T item) valueSelector) {
  final Map<K, List<V>> result = {};
  for (final element in this) {
    final key = keySelector(element);
    result.putIfAbsent(key, () => []).add(valueSelector(element));
  }

  return result;
}