Logo

Programming-Idioms

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

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.

import java.util.HashMap;
import java.util.Map;
Map<K, V> c = new HashMap<>(a);
c.putAll(b);

"... If the map previously contained a mapping for the key, the old value is replaced by the specified value."
final c = {...a, ...b};

Spread and flatten the entries of maps a and b to construct a new copy as c. Duplicate keys will favor b over a.

New implementation...
< >
programming-idioms.org