Java HashMap putAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, putAll(m) copies every mapping from the map m into this HashMap. It has the same effect as calling put(k, v) for each entry of m.

Keys that exist only in this map are kept. Keys that exist in both end up with the value from m: the old value is overwritten, not combined. The source map is not changed.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

Pass any Map whose keys and values fit this map's types.

Java
Map<String, String> settings = new HashMap<>();
settings.putAll(defaults);   // copy the defaults
settings.putAll(user);       // user values overwrite matching keys
CallWhat it does
map.putAll(other)Adds or overwrites every mapping from other.
new HashMap<>(other)Creates a new map with other's mappings.
other.forEach((k, v) -> map.merge(k, v, f))Combines values instead of overwriting.
map.putAll(new HashMap<>())Copying an empty map changes nothing.

There is no return value. To know how many keys were new, compare size() before and after the call.

Library declarations
Java
// java.util.HashMap<K, V>
public void putAll(Map<? extends K, ? extends V> m)

// Declared in Map<K, V>

Parameters

ParameterDescription
m (Map<? extends K, ? extends V>)The mappings to copy. Must not be null; may contain null keys and values.

Return Value

Return ValueDescription
voidNothing.

Compare with Similar Methods

Combining maps:

MethodHow it differs
put(k, v)Adds or overwrites a single mapping.
merge(k, v, f)Combines old and new values with a function.
putIfAbsent(k, v)Keeps existing values; loop over the source to fill gaps only.
clone()Copies a whole HashMap into a new one.

Java Examples

Example 1 — Combine Default and User Settings

Copy the defaults first, then the user's choices, so the user wins on any shared key.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapPutAllDemo {
    public static void main(String[] args) {
        Map<String, String> defaults = new HashMap<>();
        defaults.put("theme", "light");
        defaults.put("language", "en");
        defaults.put("fontSize", "14");

        Map<String, String> user = new HashMap<>();
        user.put("theme", "dark");

        Map<String, String> settings = new HashMap<>();
        settings.putAll(defaults);
        settings.putAll(user);
        System.out.println("settings: " + settings);
        System.out.println("defaults unchanged: " + defaults.get("theme"));
    }
}

How It Works

  1. Start from defaults. The first putAll copies all three default settings into the empty settings map.
  2. Later call wins. The second putAll copies theme=dark, overwriting light; the other two defaults are left alone.
  3. Source untouched. Copying never changes the source map, so defaults still says light.
  4. Copies may be sized differently. putAll into an empty map pre-sizes its table, and that sizing rule changed in JDK 19; these three keys were chosen because they print in the same order either way.

Example 2 — putAll Overwrites; merge Adds Up

Combine the stock of two shops: putAll replaces the shared item, while merge adds the quantities.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapPutAllOverwrite {
    public static void main(String[] args) {
        Map<String, Integer> shopA = new HashMap<>();
        shopA.put("rice", 10);
        shopA.put("salt", 4);

        Map<String, Integer> shopB = new HashMap<>();
        shopB.put("salt", 9);
        shopB.put("sugar", 6);

        Map<String, Integer> summed = new HashMap<>(shopA);
        shopB.forEach((item, qty) -> summed.merge(item, qty, Integer::sum));

        int before = shopA.size();
        shopA.putAll(shopB);
        System.out.println("putAll salt: " + shopA.get("salt"));
        System.out.println("merge salt: " + summed.get("salt"));
        System.out.println("new keys added by putAll: " + (shopA.size() - before));
        System.out.println("rice kept: " + shopA.get("rice"));
    }
}

How It Works

  1. Summing copy first. summed starts as a copy of shop A, and merge(..., Integer::sum) adds each of shop B's quantities to it.
  2. putAll replaces. Shop A's salt (4) is overwritten by shop B's 9; nothing is added together.
  3. merge combines. In the summing copy, salt becomes 4 + 9 = 13.
  4. Counting new keys. Only sugar was new to shop A, so the size grows from 2 to 3, and rice keeps its own value.

Example 3 — null Maps, Empty Maps, and null Entries

Pass a null map, an empty map, and a map containing a null key and a null value.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapPutAllNulls {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Ann", 5);

        Map<String, Integer> none = null;
        try {
            scores.putAll(none);
        } catch (NullPointerException e) {
            System.out.println("putAll(null) -> NullPointerException");
        }

        scores.putAll(new HashMap<>());
        System.out.println("after empty putAll: " + scores);

        Map<String, Integer> withNulls = new HashMap<>();
        withNulls.put(null, 1);
        withNulls.put("Bo", null);
        scores.putAll(withNulls);
        System.out.println("after nulls: " + scores + " size " + scores.size());
    }
}

How It Works

  1. No source at all. putAll needs a real map to read from, so a null argument throws NullPointerException.
  2. Empty source. Copying an empty map is allowed and leaves scores exactly as it was.
  3. null entries are fine. The source's null key and Bo's null value are copied like any other mapping, because HashMap accepts both.
  4. Shared bucket. The size is 3. "Ann" happens to hash to bucket 0 as well, and it was stored earlier, so it prints before the null key.

Frequently Asked Questions

Call target.putAll(source) to copy all mappings, letting source values win. Use source.forEach((k, v) -> target.merge(k, v, f)) to combine values instead.
Yes. For every key in the argument map, the value in the argument replaces the existing value.
It throws NullPointerException.
No. It only reads from the source.
No. Keys and values are shared references, so mutable values are visible through both maps.

Next: putIfAbsent()

Add a mapping only when the key is missing.

putIfAbsent() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful