associateBy<K> method

Map<K, T> associateBy<K>(
  1. K keySelector(
    1. T element
    )
)

Returns a map where every element is associated by a key produced from the keySelector function.

If two elements share the same key, the last one gets added to the map.

Example:

['a', 'ab', 'abc'].associateBy((e) => e.length); // {1: 'a', 2: 'ab', 3: 'abc'}

Implementation

Map<K, T> associateBy<K>(K Function(T element) keySelector) {
  ArgumentError.checkNotNull(keySelector, 'keySelector');
  final map = <K, T>{};
  forEach((element) {
    final key = keySelector(element);
    map[key] = element;
  });
  return map;
}