πŸ“Š Java Data Structures
Estimated reading: 4 minutes 436 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 :
Share

Java HashMap

Or Copy Link

CONTENTS
Scroll to Top