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
Syntax
map.put(key, value)
Parameters
| Parameter | Description |
|---|---|
keyK |
The key. |
valueV |
The value. |
Return value
The previous value, or null.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
map.get()· Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.map.putIfAbsent()· Add a key-value pair only if the key is missing (or mapped to null). Returns the existing value otherwise.map.merge()· Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values.- Java HashMap · tutorial