Java HashMap clear() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, clear() removes every key/value mapping from a HashMap. Afterwards size() is 0, isEmpty() is true, and every lookup returns null.

The map object itself survives, so you can keep adding to it. Every variable that refers to the same map, and every view such as keySet(), sees the cleared state. A copy made earlier keeps its own entries.

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

No arguments; returns nothing.

Java
Map<String, Integer> cart = new HashMap<>();
cart.put("milk", 2);
cart.clear();
System.out.println(cart);   // {}
CallWhat it does
map.clear()Removes every mapping; the map stays usable.
map = new HashMap<>()Points the variable at a new map; other references keep the old one.
map.keySet().clear()Same effect through a view.
map.isEmpty()true right after clear().

In OpenJDK, clear() empties the internal table but keeps its current length, so a map that once grew large keeps that capacity. Creating a new map is the way to release it; either way this is an implementation detail.

Library declarations
Java
// java.util.HashMap<K, V>
public void clear()

// Declared in Map<K, V>

Parameters

ParameterDescription
Noneclear() takes no parameters.

Return Value

Return ValueDescription
voidNothing. The map is empty afterwards.

Compare with Similar Methods

Removing many mappings:

MethodHow it differs
remove(k)Removes one mapping and returns its value.
values().removeIf(test)Removes only the mappings that match.
isEmpty()Confirms the map is empty.
clone()Take a copy first if you still need the old entries.

Java Examples

Example 1 — Empty a Shopping Cart and Reuse It

Print a cart, clear it, check it, and add a new item to the same map.

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

public class HashMapClearDemo {
    public static void main(String[] args) {
        Map<String, Integer> cart = new HashMap<>();
        cart.put("milk", 2);
        cart.put("eggs", 12);
        cart.put("bread", 1);
        System.out.println("before: " + cart + " size " + cart.size());

        cart.clear();
        System.out.println("after: " + cart + " size " + cart.size());
        System.out.println("isEmpty: " + cart.isEmpty() + ", milk: " + cart.get("milk"));

        cart.put("tea", 1);
        System.out.println("reused: " + cart);
    }
}

How It Works

  1. Three items. The cart prints its mappings in hash order with a size of 3.
  2. All gone. After clear() the map prints as {} and its size is 0.
  3. Lookups return null. get("milk") no longer finds anything, and isEmpty() confirms the map is empty.
  4. Same object, ready again. clear() does not destroy the map, so put("tea", 1) works on the very same cart.

Example 2 — clear() Affects Every Reference, Not Copies

Clear a settings map that is also referenced by a second variable, a key view, and an independent copy.

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

public class HashMapClearShared {
    public static void main(String[] args) {
        Map<String, String> settings = new HashMap<>();
        settings.put("theme", "dark");
        settings.put("lang", "en");

        Map<String, String> sameMap = settings;
        Map<String, String> snapshot = new HashMap<>(settings);
        Set<String> keys = settings.keySet();

        settings.clear();
        System.out.println("sameMap size: " + sameMap.size());
        System.out.println("keySet view empty: " + keys.isEmpty());
        System.out.println("snapshot: " + snapshot.size() + " entries, theme=" + snapshot.get("theme"));
    }
}

How It Works

  1. Two names, one map. sameMap = settings copies only the reference, so both variables point at the same HashMap.
  2. A real copy. new HashMap<>(settings) builds a separate map holding its own two mappings.
  3. Clear through either name. After settings.clear(), sameMap reports size 0 and the key view taken earlier is empty too.
  4. Copy untouched. The snapshot still has both settings, so snapshot.get("theme") returns dark.

Example 3 — Reuse One Map for Each Day's Sales

Count each day's items in the same map, clearing it at the start of every day.

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

public class HashMapClearBatches {
    public static void main(String[] args) {
        String[][] days = {
            {"pen", "ink", "pen"},
            {"ink", "pad"}
        };
        Map<String, Integer> sold = new HashMap<>();

        for (int d = 0; d < days.length; d++) {
            sold.clear();
            for (String item : days[d]) {
                sold.merge(item, 1, Integer::sum);
            }
            System.out.println("day " + (d + 1) + ": " + new TreeMap<>(sold));
        }
    }
}

How It Works

  1. One map, many batches. sold is created once outside the loop and cleared at the start of each day.
  2. Fresh counts. Without the clear(), day 2 would report ink=2 and still list two pens from day 1.
  3. Counting. merge(item, 1, Integer::sum) inserts 1 for a new item and adds 1 for a repeat, so day 1 has pen=2.
  4. Readable order. Each day's counts are printed through a sorted TreeMap copy.

Frequently Asked Questions

Call map.clear(). The map becomes empty and can be reused.
clear() empties the existing object, which every reference sees. Assigning a new map only changes that one variable; other references keep the old entries.
No. The copy is a separate map with its own entries.
Not in OpenJDK: the table keeps its length and only the entries are removed. Create a new map if you need to release that memory.
Yes. It simply does nothing visible.

Next: clone()

Make a shallow copy of the map.

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

7 people found this page helpful