Java HashMap replaceAll() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 8+

Definition

In Java, replaceAll(function) visits every mapping of a HashMap and replaces its value with function.apply(key, oldValue). Keys are never added, removed, or changed.

The function is a BiFunction<K, V, V>, usually a lambda such as (item, price) -> price * 90 / 100. Because it receives the key too, each value can be computed differently depending on its key.

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. replaceAll(BiFunction) was added in Java 8 as a default method of Map; HashMap overrides it to update its entries in place.

Syntax

Pass a lambda that maps (key, old value) to the new value.

Java
Map<String, Integer> prices = new HashMap<>();
prices.put("cap", 250);
prices.replaceAll((item, price) -> price * 90 / 100);   // cap=225
CallWhat it does
map.replaceAll((k, v) -> newV)Replaces every value.
map.replaceAll((k, v) -> k.equals(x) ? f(v) : v)Changes some values, keeps the rest.
map.replace(k, v)Replaces a single value.
map.computeIfPresent(k, f)Applies a function to one key, and can remove it.

Returning the old value unchanged is how you skip an entry; there is no way to skip without returning something.

Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

// Default method in Map<K, V>, overridden by HashMap

Parameters

ParameterDescription
function (BiFunction<? super K, ? super V, ? extends V>)Computes each new value from the key and the old value. Must not be null.

Return Value

Return ValueDescription
voidNothing; the map is updated in place.

Compare with Similar Methods

Changing many values:

MethodHow it differs
replace(k, v)Changes one existing value.
entrySet() + setValueA loop that can also skip or stop early.
compute(k, f)One key; a null result removes it.
forEach(action)Reads every mapping without changing values.

Java Examples

Example 1 — Take 10% Off Every Price

Apply one formula to every value, then print the result sorted by item name.

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

public class HashMapReplaceAllDemo {
    public static void main(String[] args) {
        Map<String, Integer> prices = new HashMap<>();
        prices.put("shirt", 800);
        prices.put("cap", 250);
        prices.put("socks", 120);

        prices.replaceAll((item, price) -> price * 90 / 100);
        System.out.println(new TreeMap<>(prices));
    }
}

How It Works

  1. One call, every entry. replaceAll runs the lambda once for each of the three items.
  2. Key ignored. The lambda receives item but only uses price, so every item gets the same formula.
  3. Integer math. Multiplying before dividing keeps precision: 800 * 90 / 100 = 720, 250 * 90 / 100 = 225, 120 * 90 / 100 = 108.
  4. Sorted view of the result. Printing through a TreeMap lists cap, shirt, socks in alphabetical order.

Example 2 — Build Labels from Each Key and Value

Turn lowercase country names into labels that include the upper-case country code.

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

public class HashMapReplaceAllLabels {
    public static void main(String[] args) {
        Map<String, String> countries = new HashMap<>();
        countries.put("in", "india");
        countries.put("jp", "japan");
        countries.put("br", "brazil");

        countries.replaceAll((code, name) ->
            code.toUpperCase() + " - " + Character.toUpperCase(name.charAt(0)) + name.substring(1));
        countries.forEach((code, label) -> System.out.println(code + " => " + label));
    }
}

How It Works

  1. Key-dependent values. Each new value is built from both the key (the code) and the old value (the country name).
  2. Capitalize. Character.toUpperCase(name.charAt(0)) raises the first letter and substring(1) appends the rest, so india becomes India.
  3. Keys unchanged. The printed keys are still lowercase: replaceAll can change values only.
  4. Alphabetical by luck. The forEach output follows the table order of the three two-letter keys; that it looks alphabetical here is a coincidence of their hash codes.

Example 3 — null Results Keep the Key; a null Function Throws

Disable large coupons by mapping them to null, then pass null as the function.

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

public class HashMapReplaceAllNulls {
    public static void main(String[] args) {
        Map<String, Integer> coupons = new HashMap<>();
        coupons.put("SAVE5", 5);
        coupons.put("SAVE50", 50);
        coupons.put("SAVE10", 10);

        coupons.replaceAll((code, pct) -> pct > 20 ? null : pct);
        System.out.println("after: " + coupons);
        System.out.println("SAVE50 still a key? " + coupons.containsKey("SAVE50"));

        try {
            coupons.replaceAll(null);
        } catch (NullPointerException e) {
            System.out.println("replaceAll(null) -> NullPointerException");
        }
    }
}

How It Works

  1. Keep or blank. The lambda returns the same percentage for small coupons and null for anything above 20.
  2. null is stored. SAVE50 now maps to null; unlike compute, replaceAll does not remove a key whose new value is null.
  3. Still present. containsKey("SAVE50") is true, so remove the key separately if it should disappear.
  4. Function required. replaceAll(null) throws NullPointerException instead of doing nothing.

Frequently Asked Questions

Call map.replaceAll((key, value) -> newValue). The lambda runs once per mapping and its result becomes the new value.
No. Only values change. To rename keys, build a new map.
In a HashMap the key stays and its value becomes null. Use entrySet().removeIf(...) to drop entries.
It throws NullPointerException.
Java 8, as a default method of Map.

Next: size()

Count the key/value mappings.

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

8 people found this page helpful