merge method

Map<K, V> merge(
  1. Map<K, V> other,
  2. V resolve(
    1. V v1,
    2. V v2
    )?
)

Merges this map with another other map. For duplicate keys, resolve determines the final value.

Example:

var map1 = {'first': 1, 'second': 2};
var map2 = {'second': 3, 'third': 4};
print(map1.merge(map2, (v1, v2) => v1 + v2)); // Output: {'first': 1, 'second': 5, 'third': 4}

Implementation

Map<K, V> merge(Map<K, V> other, V Function(V v1, V v2)? resolve) {
  final Map<K, V> result = Map<K, V>.from(this);
  other.forEach((key, value) {
    if (result.containsKey(key) && resolve != null) {
      result[key] = resolve.call(result[key] as V, value);
    } else {
      result[key] = value;
    }
  });
  return result;
}