πΊοΈ Java HashMap β Complete Guide with Syntax, Examples & Best Practices
π§² Introduction β Why HashMap Is Essential in Java
Imagine storing and retrieving student records by roll number, product prices by ID, or configuration settings by name β all in constant time. Thatβs what Java HashMap is built for.
A HashMap
lets you associate a key with a value and provides fast lookups, inserts, and deletions. Itβs one of the most powerful and frequently used classes in the Java Collections Framework.
By the end of this article, youβll understand:
β
What HashMap
is and how it works internally
β
How to create, insert, retrieve, update, and delete entries
β
How to iterate through a HashMap
β
Best practices, performance tips, and real-world examples
π What Is HashMap in Java?
πΊοΈ A HashMap is a key-value based, unordered, and non-synchronized map implementation in Java. It allows one
null
key and multiplenull
values.
π¦ Located in java.util
package
π§ Implements Map<K, V>
interface
π Uses hashing for fast access (O(1) average time)
π§ͺ Basic Syntax β Creating a HashMap
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
System.out.println(map); // Output: {1=Apple, 2=Banana, 3=Cherry}
}
}
β
put(K key, V value)
stores a value associated with the key
β
Keys must be unique β duplicate keys overwrite existing entries
π¦ Common HashMap Methods
Method | Description | Example |
---|---|---|
put(K, V) | Add or update a key-value pair | map.put(1, "Java") |
get(K) | Retrieve value by key | map.get(1) |
containsKey(K) | Checks if a key exists | map.containsKey(1) |
containsValue(V) | Checks if a value exists | map.containsValue("Java") |
remove(K) | Remove by key | map.remove(1) |
clear() | Remove all entries | map.clear() |
isEmpty() | Checks if map is empty | map.isEmpty() |
size() | Number of key-value pairs | map.size() |
π Iterating Through a HashMap
π§© Using entrySet()
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
π§© Using forEach()
(Java 8+)
map.forEach((key, value) -> System.out.println(key + ": " + value));
π Real-World Example β Product Price Map
HashMap<String, Double> prices = new HashMap<>();
prices.put("Laptop", 999.99);
prices.put("Phone", 499.49);
prices.put("Tablet", 299.99);
System.out.println("Laptop price: $" + prices.get("Laptop"));
β Easily manage key-value relationships like product catalogs, configuration settings, etc.
βοΈ Java HashMap Internal Working (Simplified)
- HashMap uses hashCode() of the key to calculate a bucket index
- If two keys hash to the same index, it uses a linked list (or tree in Java 8+)
- Load factor (default 0.75) determines when to resize
- Java 8+: switches to balanced tree if a bucket gets too many elements
π Override equals()
and hashCode()
in custom keys to avoid collisions.
β οΈ Key Notes & Limitations
- β Unordered β no guarantee of key/value order
- β Not thread-safe β use
Collections.synchronizedMap()
orConcurrentHashMap
for concurrency - β
Allows
null
key (only one) and multiplenull
values - β οΈ Poor hash function = more collisions = degraded performance
π HashMap vs TreeMap vs LinkedHashMap
Feature | HashMap | TreeMap | LinkedHashMap |
---|---|---|---|
Order | β No | β Sorted by keys | β Insertion order |
Performance | β Fastest | β Slower (O(log n)) | β Good (slightly slower) |
Null keys | β 1 allowed | β Not allowed | β 1 allowed |
Thread-safe | β No | β No | β No |
π‘ Best Practices for Using HashMap
β
Use generics to ensure type safety
β
Always override hashCode()
and equals()
when using custom keys
β
Initialize with proper capacity if size is known
β
Use computeIfAbsent()
(Java 8+) for smart initialization
β
Prefer ConcurrentHashMap
in multi-threaded applications
β Summary
HashMap
is a key-value store with constant-time operations- Allows null key, fast lookups, and dynamic resizing
- Ideal for caches, configuration maps, lookup tables, etc.
- Use with care in multi-threaded environments
β FAQs β Java HashMap
β Can I have duplicate keys in HashMap?
No. Keys must be unique. If you put an existing key again, it will overwrite the previous value.
β Can HashMap store null values?
Yes. It allows one null key and multiple null values.
β Is HashMap ordered?
No. The order of keys and values is not guaranteed. Use LinkedHashMap
to maintain insertion order.
β Is HashMap thread-safe?
No. For thread safety, use ConcurrentHashMap
or wrap it with Collections.synchronizedMap()
.
β How to sort a HashMap?
You can sort it using a TreeMap
, or sort entries using stream().sorted()
.
Share Now :