Java 25 (LTS) reference · Map and HashMap Methods

Java Map put() Method

Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.put(key, value)

Parameters

ParameterDescription
key
K
The key.
value
V
The value.

Return value

The previous value, or null.

Examples

Add and replace
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, String> capitals = new HashMap<>();
        capitals.put("Portugal", "Lisbon");
        String old = capitals.put("Portugal", "Porto?");
        System.out.println(old + " -> " + capitals.get("Portugal"));
    }
}

Output

Lisbon -> Porto?

Run this on your computer — see “Get Started” for setup.

Insertion order with LinkedHashMap
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> ages = new LinkedHashMap<>();  // keeps insertion order
        ages.put("Ana", 34);
        ages.put("Ben", 28);
        System.out.println(ages);
    }
}

Output

{Ana=34, Ben=28}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?