ποΈ Java HashMap Methods β Complete Guide with Syntax, Use Cases & Best Practices (2025)
π§² Introduction β Why Use Java HashMap Methods?
In Java, HashMap is a powerful data structure used for storing key-value pairs. Itβs part of the java.util package and allows fast retrieval, insertion, and deletion of elements β making it ideal for building caches, lookup tables, and dictionaries.
By the end of this article, youβll know:
- β
How to create and use
HashMapeffectively - β
All major
HashMapmethods with examples - β Real-world best practices for fast and reliable lookups
π What is a HashMap in Java?
A HashMap is a part of the Java Collections Framework. It implements the Map interface, storing data in key-value pairs and ensuring that:
- πΉ Keys are unique
- πΉ One key maps to one value
- πΉ Values can be duplicated
π Package:
java.util.HashMap
β οΈ Not synchronized (useConcurrentHashMapfor thread safety)
π¦ Commonly Used Java HashMap Methods
| π§© Method | π Purpose |
|---|---|
put(key, value) | Adds or updates key-value pair |
get(key) | Retrieves value by key |
remove(key) | Removes entry by key |
containsKey(key) | Checks if key exists |
containsValue(value) | Checks if value exists |
isEmpty() | Checks if map is empty |
size() | Returns number of key-value pairs |
clear() | Removes all mappings |
keySet() | Returns set of all keys |
values() | Returns collection of values |
entrySet() | Returns set of key-value pairs |
putIfAbsent(key, value) | Adds only if key is absent |
replace(key, value) | Replaces existing value |
forEach() | Iterates using lambda |
β Java HashMap Method Examples
β
1. put() and get()
HashMap<String, Integer> map = new HashMap<>();
map.put("Java", 90);
map.put("Python", 85);
System.out.println(map.get("Java")); // Output: 90
β Adds key-value pairs and retrieves the value using the key.
β
2. remove()
map.remove("Python");
System.out.println(map); // Output: {Java=90}
β
Deletes the entry with key "Python".
β
3. containsKey() and containsValue()
System.out.println(map.containsKey("Java")); // true
System.out.println(map.containsValue(100)); // false
β Checks for existence of key or value.
β
4. isEmpty() and size()
System.out.println(map.isEmpty()); // false
System.out.println(map.size()); // 1
β Returns whether the map has elements and its size.
β
5. clear() β Remove All Elements
map.clear();
System.out.println(map.isEmpty()); // true
β Empties the entire map.
β
6. keySet() and values()
map.put("C", 70);
map.put("Go", 75);
System.out.println(map.keySet()); // [C, Go]
System.out.println(map.values()); // [70, 75]
β
keySet() returns a Set of keys; values() returns a Collection of values.
β
7. entrySet() β Loop Over Entries
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
β Iterates through key-value pairs.
β
8. putIfAbsent() β Insert If Not Exists
map.putIfAbsent("C", 80); // Won't overwrite existing key
β Adds only if the key isnβt already present.
β
9. replace() β Update Existing Entry
map.replace("Go", 95);
System.out.println(map.get("Go")); // 95
β Replaces value only if key already exists.
β
10. forEach() β Lambda Style Iteration (Java 8+)
map.forEach((k, v) -> System.out.println(k + " => " + v));
β Functional style iteration for better readability.
π Summary Table of HashMap Methods
| π§ Operation | β Methods |
|---|---|
| Add/Update | put(), putIfAbsent(), replace() |
| Get | get(), containsKey(), containsValue() |
| Remove | remove(), clear() |
| Info | isEmpty(), size() |
| Access Sets | keySet(), values(), entrySet() |
| Iteration | forEach(), entrySet().iterator() |
π‘ Java HashMap Tips & Best Practices
- β
Use
putIfAbsent()to avoid accidental overwrites. - β
Use
entrySet()for efficient iteration. - β οΈ
HashMapis not thread-safe β useConcurrentHashMapin multi-threaded applications. - π Java uses hashing β override
equals()andhashCode()when using custom objects as keys.
π§ Summary β Java HashMap Methods
Javaβs HashMap is a must-know collection for efficient key-value storage and access. These methods allow you to:
- β Add, update, and remove entries easily
- β Perform fast lookups and iterations
- β Build flexible and performant apps like caches, dictionaries, and registries
βFAQs on Java HashMap Methods
β Can HashMap have duplicate keys?
No. Each key must be unique, but values can be duplicated.
β What happens if I put an existing key?
It overwrites the old value with the new one.
β How to check if a key exists before inserting?
Use containsKey() or putIfAbsent().
β How is HashMap different from TreeMap?
| Feature | HashMap | TreeMap |
|---|---|---|
| Order | No order | Sorted by keys |
| Performance | Faster | Slower |
| Null keys | Allowed | Not allowed |
β Is HashMap ordered?
No. Use LinkedHashMap to maintain insertion order.
Share Now :
