πŸ“š Java Reference
Estimated reading: 4 minutes 37 views

πŸ—‚οΈ 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 HashMap effectively
  • βœ… All major HashMap methods 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 (use ConcurrentHashMap for 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/Updateput(), putIfAbsent(), replace()
Getget(), containsKey(), containsValue()
Removeremove(), clear()
InfoisEmpty(), size()
Access SetskeySet(), values(), entrySet()
IterationforEach(), entrySet().iterator()

πŸ’‘ Java HashMap Tips & Best Practices

  • βœ… Use putIfAbsent() to avoid accidental overwrites.
  • βœ… Use entrySet() for efficient iteration.
  • ⚠️ HashMap is not thread-safe β€” use ConcurrentHashMap in multi-threaded applications.
  • πŸ“˜ Java uses hashing – override equals() and hashCode() 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?

FeatureHashMapTreeMap
OrderNo orderSorted by keys
PerformanceFasterSlower
Null keysAllowedNot allowed

❓ Is HashMap ordered?

No. Use LinkedHashMap to maintain insertion order.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java HashMap Methods

Or Copy Link

CONTENTS
Scroll to Top