HashMap.put() / get() / remove()
The core methods for adding, retrieving, and deleting key-value pairs in a HashMap, providing efficient O(1) average time complexity.
HashMap<K, V> map = new HashMap<>();
map.put(K key, V value)
V map.get(Object key)
V map.remove(Object key)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
The core methods for adding, retrieving, and deleting key-value pairs in a HashMap, providing efficient O(1) average time complexity.
A `HashMap` in Java is an implementation of the `Map` interface, storing data in key-value pairs. It uses hashing to store and retrieve elements, offering highly efficient operations. The `put(K key, V value)` method inserts or updates a key-value pair. If the key already exists, its associated value is updated, and the old value is returned; otherwise, `null` is returned. The `get(Object key)` method retrieves the value associated with a specified key, returning `null` if the key is not found. The `remove(Object key)` method deletes the key-value pair for the specified key, returning the removed value or `null` if the key was not present. All three operations (`put`, `get`, `remove`) have an average time complexity of O(1) (constant time), making `HashMap` suitable for scenarios requiring fast lookups and modifications. In the worst-case scenario (due to hash collisions or poor hash function), the complexity can degrade to O(n), where `n` is the number of elements. `HashMap` allows one `null` key and multiple `null` values. It is not thread-safe; for concurrent access, `ConcurrentHashMap` should be used.
Quick reference
Syntax
HashMap<K, V> map = new HashMap<>();
map.put(K key, V value)
V map.get(Object key)
V map.remove(Object key)
Inputs
Parameters
See it in practice
Examples
Adding and retrieving elements
import java.util.HashMap;
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println("Alice's age: " + ages.get("Alice"));
System.out.println("Charlie's age (not found): " + ages.get("Charlie"));Alice's age: 30 Charlie's age (not found): null
Demonstrates how to add key-value pairs using `put()` and retrieve values using `get()`. `get()` returns `null` for non-existent keys.
Updating a value and removing an element
import java.util.HashMap;
HashMap<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Germany", "Berlin");
System.out.println("Original capitals: " + capitals);
// Update
capitals.put("France", "Lyon"); // Paris is replaced by Lyon
System.out.println("Capitals after update: " + capitals);
// Remove
String removedCapital = capitals.remove("Germany");
System.out.println("Removed capital: " + removedCapital);
System.out.println("Capitals after removal: " + capitals);Original capitals: {Germany=Berlin, France=Paris} Capitals after update: {Germany=Berlin, France=Lyon} Removed capital: Berlin Capitals after removal: {France=Lyon}
Shows how `put()` updates an existing key's value and how `remove()` deletes an entry, returning the value that was removed.
Using null key and null values
import java.util.HashMap;
HashMap<String, String> settings = new HashMap<>();
settings.put("theme", "dark");
settings.put(null, "default"); // Null key
settings.put("language", null); // Null value
System.out.println("Theme: " + settings.get("theme"));
System.out.println("Null key value: " + settings.get(null));
System.out.println("Language: " + settings.get("language"));Theme: dark Null key value: default Language: null
Demonstrates `HashMap`'s ability to store one `null` key and multiple `null` values.
Debug faster
Common Errors
NullPointerException when retrieving primitive types
Cause: If `get()` returns `null` (because the key is not found) and you try to auto-unbox it into a primitive type (e.g., `int`), a `NullPointerException` will occur.
Fix: Always check for `null` when retrieving values from a `HashMap` if the value type is a wrapper class that might be auto-unboxed, or use `getOrDefault()`.
import java.util.HashMap;
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 100);
// int aliceScore = scores.get("Alice"); // Works fine
// int bobScore = scores.get("Bob"); // This would cause NPE if unboxed directly
Integer bobScoreWrapper = scores.get("Bob");
if (bobScoreWrapper != null) {
int bobScore = bobScoreWrapper;
System.out.println("Bob's score: " + bobScore);
} else {
System.out.println("Bob's score not found.");
}
// Alternative using getOrDefault (Java 8+)
int charlieScore = scores.getOrDefault("Charlie", 0);
System.out.println("Charlie's score: " + charlieScore);Runtime support
Compatibility
Source: Oracle Java Documentation
Common questions
Frequently Asked Questions
The core methods for adding, retrieving, and deleting key-value pairs in a HashMap, providing efficient O(1) average time complexity.
key: The key with which the specified value is to be associated. value: The value to be associated with the specified key. key: The key whose associated value is to be returned or removed.
NullPointerException when retrieving primitive types: Always check for `null` when retrieving values from a `HashMap` if the value type is a wrapper class that might be auto-unboxed, or use `getOrDefault()`.