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 :
