How to Put and Get in HashMap in Java - Simple Guide
In Java, you use
put(key, value) to add a key-value pair to a HashMap and get(key) to retrieve the value for a given key. The put method stores the value, and the get method returns the value or null if the key is not found.Syntax
The put method adds or updates a key-value pair in the HashMap. The get method retrieves the value for a given key.
- put(key, value): Adds the value with the specified key.
- get(key): Returns the value associated with the key or
nullif not found.
java
HashMap<KeyType, ValueType> map = new HashMap<>(); map.put(key, value); // Store value ValueType value = map.get(key); // Retrieve value
Example
This example shows how to create a HashMap, add key-value pairs using put, and get values using get. It prints the stored values and shows what happens when a key is missing.
java
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); // Put key-value pairs map.put("apple", 10); map.put("banana", 20); map.put("orange", 30); // Get values System.out.println("apple: " + map.get("apple")); System.out.println("banana: " + map.get("banana")); // Try to get a key that does not exist System.out.println("grape: " + map.get("grape")); } }
Output
apple: 10
banana: 20
grape: null
Common Pitfalls
Common mistakes include:
- Using
geton a key that does not exist returnsnull, which can causeNullPointerExceptionif not checked. - Using mutable objects as keys without proper
hashCodeandequalsmethods can cause unexpected behavior. - Forgetting to import
java.util.HashMap.
java
import java.util.HashMap; public class PitfallExample { public static void main(String[] args) { HashMap<String, String> map = new HashMap<>(); map.put("key1", "value1"); // Wrong: assuming key exists without check String val = map.get("key2"); // This will cause NullPointerException if you call val.length() // System.out.println(val.length()); // Uncommenting causes error // Right: check for null if (val != null) { System.out.println(val.length()); } else { System.out.println("Key not found"); } } }
Output
Key not found
Quick Reference
| Method | Description | Example |
|---|---|---|
| put(key, value) | Adds or updates a key-value pair | map.put("name", "Alice"); |
| get(key) | Retrieves value for the key or null | map.get("name"); |
| containsKey(key) | Checks if key exists | map.containsKey("name"); |
| remove(key) | Removes key-value pair | map.remove("name"); |
Key Takeaways
Use put(key, value) to add or update entries in a HashMap.
Use get(key) to retrieve values; it returns null if the key is missing.
Always check for null after get() to avoid errors.
HashMap keys should have proper hashCode and equals implementations.
Import java.util.HashMap before using it.