What changed in HashMap in Java 8?

Java 8 introduced significant improvements to HashMap to enhance performance, especially in scenarios involving a large number of hash collisions. The most important change was replacing long Linked Lists with Red-Black Trees when a bucket becomes heavily populated. This reduced the worst-case lookup time and made HashMap more efficient for large datasets.

Key Points

HashMap Before Java 8

When multiple keys mapped to the same bucket

Bucket

KeyA -> KeyB -> KeyC -> KeyD

HashMap stored all colliding entries in a Linked List.

Retrieval Process

1. Find the bucket using hashCode().

2. Traverse the Linked List.

3. Compare each key using equals().

4. Return the matching value.

Problem

As the number of collisions increased, searching became slower.

Worst-Case Complexity

O(n)

HashMap in Java 8

Java 8 introduced a new optimization.

If the number of nodes in a bucket exceeds a threshold (8 by default), the Linked List is converted into a Red-Black Tree.

Before Treeification

Bucket

KeyA -> KeyB -> KeyC -> KeyD -> KeyE -> KeyF -> KeyG -> KeyH -> KeyI

After Treeification

                KeyE
              /      \

KeyC KeyG

/ \ / \

KeyA KeyD KeyF KeyI

Benefits

Worst-Case Complexity

O(log n)

When Does Treeification Happen?

Treeification occurs only when

Otherwise

Why Red-Black Tree?

Red-Black Tree is a self-balancing binary search tree.

Advantages

Complexities

Search → O(log n)

Insert  → O(log n)

Delete  → O(log n)

Example

Suppose many keys generate the same hash value.

Before Java 8

Bucket

Key1 -> Key2 -> Key3 -> Key4 -> Key5

Searching Key5 requires traversing multiple nodes.

Java 8

Bucket

Red-Black Tree

Searching becomes significantly faster because the tree structure reduces comparisons.

Other Improvements in Java 8 HashMap

Comparison

Java 7 HashMap

Java 8 HashMap

Real-World Impact

Consider a caching system storing millions of entries.

Before Java 8

Java 8

Interview Tip

A concise interview answer is

Before Java 8, HashMap handled collisions using Linked Lists, which could degrade lookup performance to O(n) when many entries occupied the same bucket. Java 8 introduced Red-Black Trees for buckets containing more than eight entries, reducing the worst-case lookup time to O(log n) and significantly improving performance in collision-heavy scenarios.

Last updated: 11 November 2026

Previous question: How does a HashMap handle collisions in Java?

Next question: Can we use a custom class as a key in a HashMap?

More Core Java - Level II interview questions

All Core Java - Level II questions