groupBy<S, T> method

Map<T, List<S>> groupBy<S, T>(
  1. T key(
    1. S
    )
)

Implementation

Map<T, List<S>> groupBy<S, T>(T Function(S) key) {
  // Create an empty map to store the grouped elements.
  Map<T, List<S>> map = <T, List<S>>{};

  // Iterate through the elements in the list.
  for (var element in this) {
    // Use the 'key' function to determine the grouping key for the element.
    T elementKey = key(element);

    // If the key does not exist in the map, initialize it with an empty list.
    // Then, add the element to the list associated with that key.
    (map[elementKey] ??= []).add(element);
  }

  // Return the map of grouped elements.
  return map;
}