renameKeys method

  1. @useResult
Map<K, V> renameKeys(
  1. Map<K, K> oldToNew
)

New map with keys renamed according to oldToNew. Keys absent from oldToNew are kept as-is. If two keys map to the same target, the later one in iteration order wins (a genuine collision is inherently lossy). Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
Map<K, V> renameKeys(Map<K, K> oldToNew) {
  // Single pass into a fresh map: read the NEW key for each ORIGINAL entry
  // (`oldToNew[k] ?? k`) and write it once. The previous version mutated the
  // copy it was iterating, so a chained rename ({'a':'b','b':'c'}) overwrote
  // 'b' before renaming it and lost data; it also dropped null values.
  final Map<K, V> out = <K, V>{};
  forEach((K k, V v) {
    out[oldToNew[k] ?? k] = v;
  });
  return out;
}