groupBy<K> method

  1. @useResult
KtMap<K, KtList<T>> groupBy<K>(
  1. K keySelector(
    1. T
    )
)

Groups elements of the original collection by the key returned by the given keySelector function applied to each element and returns a map where each group key is associated with a list of corresponding elements.

The returned map preserves the entry iteration order of the keys produced from the original collection.

Implementation

@useResult
KtMap<K, KtList<T>> groupBy<K>(K Function(T) keySelector) {
  final groups = linkedMapFrom<K, KtList<T>>();
  for (final element in iter) {
    final key = keySelector(element);
    final list = KtMutableMapExtensions(groups)
        .getOrPut(key, () => mutableListOf<T>()) as KtMutableList<T>;
    list.add(element);
  }
  return groups;
}