associateWith<V> method
Map<T, V>
associateWith<V>(
- V valueSelector(
- T value
Returns a Map
containing the elements paired with the value from
valueSelector
.
If the source list contains duplicated keys, only one of them will be left on the map.
The iteration order of the list is preserved.
final charCodes = [72, 69, 76, 76, 79]; // second 76 is ignored
final fromCharCode = charCodes.associateWith(
(code) => String.fromCharCode(code),
);
print(fromCharCode); // {72: 'H', 69: 'E', 76: 'L', 79: 'O'}
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 byName = scientists.associateWith((value) => value.lastName);
print(byName); // {Grace Hopper: Hopper, Jacob Bernoulli: Bernoulli, Johann Bernoulli: Bernoulli}
Implementation
Map<T, V> associateWith<V>(V Function(T value) valueSelector) {
return associate((key) => Pair(key, valueSelector(key)));
}