associate<K, V> method
Returns a Map containing key-value pairs that are provided by
transform.
If any of the returned Pairs 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.associate(
(code) => Pair(code, String.fromCharCode(code)),
);
// 76: L only occurs once because only the last same key gets added.
print(byCharCode); // {72: 'H', 69: 'E', 76: 'L', 79: 'O'}
final names = ['Grace Hopper', 'Jacob Bernoulli', 'Johann Bernoulli'];
final byLastName = names.associate((value) {
final split = value.split(' ');
return Pair(split[1], split[0]);
});
// Jacob Bernoulli does not occur, because the same key gets overwritten.
print(byLastName); // {Hopper: Grace, Bernoulli: Johann}
Implementation
Map<K, V> associate<K, V>(Pair<K, V> Function(T value) transform) {
return {for (final e in map(transform)) e.key: e.value};
}