Java HashMap
A Java HashMap stores data as key-value pairs. Each key is used to find one value, like using a name to look up a score or a product code to look up a price.
HashMap is part of java.util. It is useful when you want fast lookup by key instead of searching through a list item by item.
Create A HashMap
Import java.util.HashMap, then choose the type for the keys and the type for the values. For example, HashMap<String, Integer> means the keys are strings and the values are integers.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Mia", 95);
scores.put("Noah", 88);
scores.put("Ava", 91);
System.out.println("Mia: " + scores.get("Mia"));
System.out.println("Has Noah: " + scores.containsKey("Noah"));
System.out.println("Students: " + scores.size());
}
}
Output:
Mia: 95
Has Noah: true
Students: 3
The put() method adds a key-value pair. The get() method returns the value for a key, and containsKey() checks whether a key exists.
Keys Must Be Unique
A map cannot store the same key twice. If you call put() with a key that already exists, the new value replaces the old value.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Kyoto");
capitals.put("Japan", "Tokyo");
System.out.println(capitals.get("Japan"));
System.out.println(capitals.getOrDefault("Italy", "Unknown"));
}
}
Output:
Tokyo
Unknown
The second value for "Japan" replaces "Kyoto" with "Tokyo". The getOrDefault() method is helpful when a key might not exist.
Remove And Check Values
Use remove(key) to delete a key-value pair. Use containsValue(value) when you need to check whether any key has a certain value.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Double> prices = new HashMap<>();
prices.put("notebook", 3.50);
prices.put("pen", 1.25);
prices.put("folder", 2.00);
prices.remove("pen");
System.out.println(prices.containsKey("pen"));
System.out.println(prices.containsValue(2.00));
System.out.println("Items: " + prices.size());
}
}
Output:
false
true
Items: 2
After remove("pen"), the key "pen" is no longer in the map. The folder price is still present, so containsValue(2.00) returns true.
Loop Through A HashMap
You can loop through a map’s keys, values, or entries. An entry contains both the key and the value. A HashMap does not guarantee the order of its entries, so do not write code that depends on the loop order.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> inventory = new HashMap<>();
inventory.put("shirts", 12);
inventory.put("hats", 5);
inventory.put("shoes", 8);
int total = 0;
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
total += entry.getValue();
}
System.out.println("Total items: " + total);
}
}
Output:
Total items: 25
This loop uses entrySet() because it needs each key-value pair. The example only adds the values, so the result is the same no matter which order the entries are visited.
Common HashMap Methods
put(key, value)adds or replaces a value for a key.get(key)returns the value for a key, ornullif the key is not found.getOrDefault(key, defaultValue)returns a fallback value when the key is missing.containsKey(key)checks whether a key exists.containsValue(value)checks whether any key has that value.remove(key)removes a key-value pair.size()returns the number of key-value pairs.clear()removes all pairs.
Common Mistakes
- Forgetting
import java.util.HashMap;. - Expecting a
HashMapto keep insertion order. UseLinkedHashMapfor insertion order orTreeMapfor sorted keys. - Using
get()and forgetting that it can returnnullwhen the key does not exist. - Trying to use primitive generic types such as
HashMap<String, int>instead of wrapper types such asHashMap<String, Integer>.
Takeaway: use HashMap when each value should be stored and found by a unique key.
