Syntax
HashMap<KeyType, ValueType> map = new HashMap<>();Examples
Creating and Adding Entries
Building a HashMap and adding key-value pairs.
import java.util.HashMap;
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Fola", 21);
ages.put("Zain", 22);
ages.put("Jamal", 20);
System.out.println(ages); // {Fola=21, Zain=22, Jamal=20} (order not guaranteed)
System.out.println(ages.get("Zain")); // 22Checking, Updating, and Removing
Common operations for working with map entries.
import java.util.HashMap;
HashMap<String, Integer> stock = new HashMap<>();
stock.put("apples", 50);
stock.put("bananas", 30);
System.out.println(stock.containsKey("apples")); // true
System.out.println(stock.getOrDefault("mango", 0)); // 0 - safe default
stock.put("apples", 45); // overwrites the existing value
stock.remove("bananas");
System.out.println(stock); // {apples=45}Iterating Over a HashMap
Looping through keys, values, or both together.
import java.util.HashMap;
import java.util.Map;
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
for (String key : scores.keySet()) {
System.out.println(key + ": " + scores.get(key));
}
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}Useful HashMap Methods
Modern convenience methods like putIfAbsent, compute, and merge.
import java.util.HashMap;
HashMap<String, Integer> wordCount = new HashMap<>();
String[] words = {"apple", "banana", "apple", "cherry", "apple"};
for (String word : words) {
wordCount.merge(word, 1, Integer::sum); // increments count, or sets to 1 if new
}
System.out.println(wordCount); // {banana=1, cherry=1, apple=3}Best practices
- Use getOrDefault() or putIfAbsent() instead of manual containsKey() + get() checks, for cleaner and more efficient code
- Use merge() or compute() for update-in-place patterns like counting occurrences, rather than a manual get-then-put sequence
- Choose LinkedHashMap if you need predictable insertion-order iteration, or TreeMap if you need keys kept in sorted order
- Always override equals() and hashCode() properly on any custom class you use as a HashMap key, or lookups will not behave correctly
At a glance
- Purpose
- General-purpose application development
- File extension
- .java
- Runs in
- Java Virtual Machine
- Usually used with
- JDK and Java libraries
Specifications & further reading
Related Java documentation
ArrayList
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashSet
HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.TreeMap & TreeSet
TreeMap and TreeSet are sorted collections backed by a red-black tree, automatically keeping their keys (or elements) in ascending order at all times. This ordering comes at a cost - operations run in logarithmic time rather than the constant time of HashMap/HashSet - but it's invaluable when you need sorted iteration, range queries, or to quickly find the smallest or largest element.
ArrayList is a resizable array implementation of the List interface, part of java.util. Unlike a plain array, an ArrayList automatically grows as elements are added, and it provides a rich set of methods for adding, removing, searching, and iterating. Since generics require object types, an ArrayList of primitives (like int) actually stores their wrapper class (Integer) via autoboxing.LinkedList
LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.HashSet
HashSet is a collection that stores unique elements with no guaranteed ordering, backed by a HashMap internally. Adding a duplicate element has no effect, since HashSet automatically enforces uniqueness. It provides constant-time (average case) performance for adding, removing, and checking membership, making it ideal for deduplication and fast lookups.TreeMap & TreeSet
TreeMap and TreeSet are sorted collections backed by a red-black tree, automatically keeping their keys (or elements) in ascending order at all times. This ordering comes at a cost - operations run in logarithmic time rather than the constant time of HashMap/HashSet - but it's invaluable when you need sorted iteration, range queries, or to quickly find the smallest or largest element.