toMap<K> method

Map<K, E> toMap<K>(
  1. K keyProvider(
    1. E item
    )
)

Converts this iterable to a Map using keyProvider to generate keys.

Each item becomes a value in the map with its key determined by keyProvider. If multiple items produce the same key, only the last item is retained. Returns an empty map if this iterable is null.

Example:

List<String>? words = ['apple', 'banana', 'cherry'];
Map<int, String> map = words.toMap((w) => w.length); // {5: 'apple', 6: 'banana', 6: 'cherry'}
// Note: 'banana' is overwritten by 'cherry' since they have the same length

Implementation

Map<K, E> toMap<K>(K Function(E item) keyProvider) {
  Map<K, E> map = {};
  if (this == null) return map;

  for (var item in this!) {
    map[keyProvider(item)] = item;
  }

  return map;
}