mergeWith method

Map<K, V> mergeWith(
  1. Map<K, V> other,
  2. V combine(
    1. V value1,
    2. V value2
    )
)

Merges two maps, using a custom combine function when keys overlap.

Example:

// Below, the `combine` function adds the values of overlapping keys.
final map1 = {'a': 1, 'b': 2};
final map2 = {'b': 3, 'c': 4};
final merged = map1.mergeWith(map2, (value1, value2) => value1 + value2);
print(merged); // Output: {'a': 1, 'b': 5, 'c': 4}

// and below, the `combine` function make changes to the values of overlapping keys.
final map1 = {'name': 'Hussein Shakir', 'job': 'Flutter Developer'};
final map2 = {'job': 'Senior', 'city': 'World'};
final merged = map1.mergeWith(map2, (value1, value2) => "${value2} ${value1}");
print(merged); // Output: {'name': 'Hussein Shakir', 'job': 'Senior Flutter Developer', 'city': 'World'}

Implementation

Map<K, V> mergeWith(Map<K, V> other, V Function(V value1, V value2) combine) {
  final result = Map<K, V>.from(this);
  other.forEach((key, value) {
    if (result.containsKey(key)) {
      result[key] = combine(result[key] as V, value);
    } else {
      result[key] = value;
    }
  });
  return result;
}