Java TreeMap putAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, putAll(m) copies every mapping from the map m into this TreeMap. The effect is the same as calling put(k, v) once for each entry of m: new keys are inserted in sorted order, and keys that already exist get the value from m.

The target map's ordering wins. It does not matter whether m is a HashMap, a LinkedHashMap, or a TreeMap sorted another way: after the copy, every key sits where this map's comparator puts it. The source map is not changed.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

Pass any Map whose key and value types fit this map.

Java
TreeMap<String, Integer> catalog = new TreeMap<>();
catalog.putAll(prices);          // copy and sort
catalog.putAll(newPrices);       // later values overwrite matching keys
CallWhat it does
tree.putAll(hashMap)Copies an unordered map and sorts its keys.
new TreeMap<>(otherMap)Creates a sorted copy in one step.
tree.putAll(other)Overwrites values for keys found in both maps.
tree.putAll(null)Throws NullPointerException.

There is no return value. Compare size() before and after the call to find out how many keys were new.

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

// Declared in Map<K, V>

Parameters

ParameterDescription
map (Map<? extends K, ? extends V>)The mappings to copy. Must not be null. Its keys must be comparable with this map's keys.

Return Value

Return ValueDescription
voidNothing.

Compare with Similar Methods

Other ways to fill a TreeMap:

MethodHow it differs
put(k, v)Adds or overwrites one mapping.
merge(k, v, f)Combines old and new values instead of overwriting.
clone()Copies a whole TreeMap, comparator included.
HashMap.putAll(m)Same copy, but the result is unordered.

Java Examples

Example 1 — Add New Arrivals to a Sorted Catalog

Copy a second price list into the catalog; the shared item takes the newer price.

Java
import java.util.TreeMap;

public class TreeMapPutAllCatalog {
    public static void main(String[] args) {
        TreeMap<String, Integer> catalog = new TreeMap<>();
        catalog.put("lamp", 25);
        catalog.put("desk", 120);

        TreeMap<String, Integer> newArrivals = new TreeMap<>();
        newArrivals.put("chair", 45);
        newArrivals.put("lamp", 22);
        newArrivals.put("shelf", 60);

        catalog.putAll(newArrivals);
        System.out.println(catalog);
        System.out.println("lamp now costs " + catalog.get("lamp"));
        System.out.println("newArrivals still has " + newArrivals.size() + " items");
    }
}

How It Works

  1. Two new products slot in. chair and shelf did not exist in the catalog, so they are inserted around desk and lamp in alphabetical order.
  2. The shared product is overwritten. lamp appears in both maps; the copy behaves like put, so 22 from newArrivals replaces 25.
  3. Read-only for the source. newArrivals keeps its three items; putAll only reads from the map you pass in.

Example 2 — Sort a HashMap by Copying It

City populations (in thousands) live in a HashMap; copying them into a TreeMap puts the cities in A-to-Z order.

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

public class TreeMapPutAllSortHashMap {
    public static void main(String[] args) {
        Map<String, Integer> population = new HashMap<>();
        population.put("Oslo", 709);
        population.put("Bergen", 291);
        population.put("Trondheim", 212);
        population.put("Alta", 21);

        TreeMap<String, Integer> sorted = new TreeMap<>();
        sorted.putAll(population);
        System.out.println("A to Z: " + sorted);
        System.out.println("first city: " + sorted.firstKey() + ", last city: " + sorted.lastKey());
    }
}

How It Works

  1. Source order is irrelevant. The HashMap hands out its entries in hash order, but each one is placed by comparing city names, so the result is always the same.
  2. Sorted by key, not by value. Trondheim (212) comes last although Oslo (709) is larger: a TreeMap orders keys only.
  3. Ends of the range. firstKey() and lastKey() now give the alphabetically first and last city, something a HashMap cannot answer cheaply.

Example 3 — The Target Map's Comparator Decides the Order

Copy a year-sorted map into a map that sorts newest first, then pass null by mistake.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapPutAllTargetOrder {
    public static void main(String[] args) {
        TreeMap<Integer, String> byYear = new TreeMap<>();
        byYear.put(2019, "v1");
        byYear.put(2023, "v3");
        byYear.put(2021, "v2");

        TreeMap<Integer, String> newestFirst = new TreeMap<>(Comparator.reverseOrder());
        newestFirst.putAll(byYear);
        System.out.println("oldest first: " + byYear);
        System.out.println("newest first: " + newestFirst);

        try {
            newestFirst.putAll(null);
        } catch (NullPointerException e) {
            System.out.println("putAll(null): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Same entries, opposite order. Both maps hold the three releases, but newestFirst was built with Comparator.reverseOrder(), so 2023 leads.
  2. No order is copied. putAll transfers keys and values only; each map keeps the comparator it was created with.
  3. A null source fails fast. The method asks the argument for its size first, so putAll(null) throws NullPointerException before touching the map.

Frequently Asked Questions

It overwrites them. For a key found in both maps, the value from the map you pass in replaces the current value, exactly like put().
Copy it into a TreeMap, either with treeMap.putAll(hashMap) or new TreeMap<>(hashMap). The keys are then kept in natural order.
No. Every key is placed by the target TreeMap's own ordering, so the source order never matters.
It throws NullPointerException. A null key inside the source map also throws NullPointerException under natural ordering.
No. Keys and values are shared references. If a value is a mutable object such as a list, both maps see changes to it.

Next: putFirst()

Java 21 SequencedMap method that a TreeMap always rejects.

putFirst() 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.

14 people found this page helpful