Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #334 Combine 2 maps

Create the new map c containing all of the (key, value) entries of the two maps a and b.

Explain what happens for keys existing in both a and b.

final c = {...a, ...b};
c := make(M, len(a)+len(b))
for k, v := range a {
	c[k] = v
}
for k, v := range b {
	c[k] = v
}
let c = {...a, ...b}
import java.util.HashMap;
import java.util.Map;
Map<K, V> c = new HashMap<>(a);
c.putAll(b);
fgl
type
  TKey = TSomeType;
  TData = TSomeOtherType;
  TMap = specialize TFPGMap<TKey, TData>;

...
  c := TMap.Create;
  for idx := 0 to a.count-1 do
  begin
    c.Add(a.keys[idx],a.data[idx]);
  end;
  for idx := 0 to b.count-1 do
  begin
    c.AddOrSetData(b.keys[idx],b.data[idx]);
  end;
%c = (%a, %b);
c = {**a, **b}
c = a | b
c = a.merge(b)

New implementation...
programming-idioms.org