groupByAndMap<K, V> method
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;
}