fromIterable<K, V, I> static method

IMap<K, V> fromIterable<K, V, I>(
  1. Iterable<I> iterable, {
  2. K keyMapper(
    1. I
    )?,
  3. V valueMapper(
    1. I
    )?,
  4. ConfigMap? config,
})

Creates an IMap instance in which the keys and values are computed from the iterable.

For each element of the iterable it computes a key/value pair, by applying keyMapper and valueMapper respectively.

The example below creates a new Map from a List. The keys of map are list values converted to strings, and the values of the map are the squares of the list values:

List<int> list = [1, 2, 3];
IMap<String, int> map = IMap.fromIterable(
  list,
  keyMapper: (item) => item.toString(),
  valueMapper: (item) => item * item),
);
// The code above will yield:
// {
//   "1": 1,
//   "2": 4,
//   "3": 9,
// }

If no values are specified for keyMapper and valueMapper, the default is the identity function.

The keys computed by the source iterable do not need to be unique. The last occurrence of a key will simply overwrite any previous value.

See also: IMap.fromIterables

Implementation

static IMap<K, V> fromIterable<K, V, I>(
  Iterable<I> iterable, {
  K Function(I)? keyMapper,
  V Function(I)? valueMapper,
  ConfigMap? config,
}) {
  config ??= defaultConfig;
  keyMapper ??= (I i) => i as K;
  valueMapper ??= (I i) => i as V;

  Map<K, V> map = ListMap.fromEntries(
    iterable.map(
      (item) => MapEntry(keyMapper!(item), valueMapper!(item)),
    ),
    sort: config.sort,
  );

  return IMap._(map, config: config);
}