associateBy<K> method

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

Returns a Map containing the elements indexed by the key from keySelector.

If any of the returned keys would contain the same key, the last one gets added to the map.

The iteration order of the list is preserved.

final charCodes = [72, 69, 76, 76, 79];
final byCharCode = charCodes.associateBy(
  (code) => String.fromCharCode(code),
);

// L: 76 only occurs once because only the last same key gets added.
print(byCharCode); // {'H': 72, 'E': 69, 'L': 76, 'O': 79}
class Person {
  const Person(this.firstName, this.lastName);

  final String firstName;

  final String lastName;

  @override
  String toString() => '$firstName $lastName';
}

final scientists = [
  Person('Grace', 'Hopper'),
  Person('Jacob', 'Bernoulli'),
  Person('Johann', 'Bernoulli'),
];

final byLastName = scientists.associateBy((value) => value.lastName);

// Jacob Bernoulli does not occur, because the same key gets overwritten.
print(byLastName); // {Hopper: Grace Hopper, Bernoulli: Johann Bernoulli}

Implementation

Map<K, T> associateBy<K>(K Function(T value) keySelector) {
  return associate((value) => Pair(keySelector(value), value));
}