πŸ“š Java Reference
Estimated reading: 4 minutes 314 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 :
Share

Java HashMap Methods

Or Copy Link

CONTENTS
Scroll to Top