πŸ“Š Java Data Structures
Estimated reading: 4 minutes 38 views

πŸ—ΊοΈ 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 multiple null 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

MethodDescriptionExample
put(K, V)Add or update a key-value pairmap.put(1, "Java")
get(K)Retrieve value by keymap.get(1)
containsKey(K)Checks if a key existsmap.containsKey(1)
containsValue(V)Checks if a value existsmap.containsValue("Java")
remove(K)Remove by keymap.remove(1)
clear()Remove all entriesmap.clear()
isEmpty()Checks if map is emptymap.isEmpty()
size()Number of key-value pairsmap.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)

  1. HashMap uses hashCode() of the key to calculate a bucket index
  2. If two keys hash to the same index, it uses a linked list (or tree in Java 8+)
  3. Load factor (default 0.75) determines when to resize
  4. 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() or ConcurrentHashMap for concurrency
  • βœ… Allows null key (only one) and multiple null values
  • ⚠️ Poor hash function = more collisions = degraded performance

πŸ“Š HashMap vs TreeMap vs LinkedHashMap

FeatureHashMapTreeMapLinkedHashMap
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 :

Leave a Reply

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

Share

Java HashMap

Or Copy Link

CONTENTS
Scroll to Top