Ask Difference

HashMap in Java vs. TreeMap in Java — What's the Difference?

By Tayyaba Rehman — Published on January 14, 2024
HashMap in Java provides unordered, O(1) time complexity for operations, using hashing. TreeMap is ordered by keys, with O(log n) time complexity, using a red-black tree.
HashMap in Java vs. TreeMap in Java — What's the Difference?

Difference Between HashMap in Java and TreeMap in Java

ADVERTISEMENT

Key Differences

HashMap in Java is a collection that stores key-value pairs and uses hashing to compute an index where these values are stored. This makes most operations such as get() and put() run in constant time (O(1)). The elements in a HashMap are not sorted in any order. Conversely, TreeMap in Java is a map implementation that guarantees the keys are sorted according to their natural order or by a specified Comparator. As a result, operations like get() and put() have O(log n) time complexity because it uses a red-black tree structure.
The internal structure of a HashMap is an array of nodes, where each node represents a key-value pair. The keys are not stored in any particular order, and there is no guarantee that the order will remain constant over time. TreeMap, on the other hand, is a navigable map and sorts its entries based on the natural ordering of its keys or by a specified comparator provided at the map's creation time.
In terms of null keys, HashMap allows one null key and multiple null values, which is often sufficient for applications where sorting is not necessary. TreeMap does not allow null keys (as it cannot compare null with other keys), but it does allow multiple null values. This distinction is important when keys are expected to be comparable and ordered.
Collision handling in HashMap is a consideration since hashing can lead to different keys producing the same index. HashMap addresses this by using a linked list or binary tree (from Java 8 onwards) to store multiple items at the same index. TreeMap, however, does not have this problem because it stores each key-value pair in a separate node within a balanced tree structure, with each node connected to two other nodes, ensuring the balance of the tree.
Performance-wise, HashMap is generally faster than TreeMap for inserting and accessing elements because it provides constant time performance for the basic operations when the hash function disperses the elements properly among the buckets. TreeMap, though slower with logarithmic time complexity for basic operations, has the advantage of maintaining a consistent order and offering several handy methods like firstEntry(), lastEntry(), headMap(), tailMap(), which makes it the preferred choice when sorted data is required.
ADVERTISEMENT

Comparison Chart

Ordering

Unordered
Sorted by keys

Time Complexity

O(1) for get/put
O(log n) for get/put

Internal Structure

Hash table
Red-black tree

Null Keys

Allows one null key
Does not allow null keys

Key Comparison

Keys need not be comparable
Keys must be comparable

Compare with Definitions

HashMap in Java

HashMap does not guarantee any order of its entries.
System.out.println(scoreMap); may print the scores in a different order each time with a HashMap.

TreeMap in Java

TreeMap does not allow null keys but allows multiple null values.
FileExtensions.put(pdf, null); adds a null value with a non-null key in a TreeMap.

HashMap in Java

HashMap is unsynchronized and may be converted to synchronized with Collections.synchronizedMap.
Map m = Collections.synchronizedMap(new HashMap()); makes a HashMap thread-safe.

TreeMap in Java

It requires that the keys implement the Comparable interface or a Comparator be provided.
PersonTreeMap.put(new Person(John), Verified); requires that Person implements Comparable.

HashMap in Java

A HashMap is an associative array that maps keys to values with a hash table.
UserMap = new HashMap<>(); creates a new HashMap for storing user information.

TreeMap in Java

Provides O(log n) access times for get and put operations.
OrderTreeMap.put(123, Order Details); adds an order to the TreeMap with logarithmic time complexity.

HashMap in Java

It offers constant-time performance for get and put, assuming the hash function disperses elements properly.
PriceMap.put(apple, 0.99); quickly inserts a price into a HashMap.

TreeMap in Java

A TreeMap stores key-value pairs in a red-black tree, maintaining a sorted order.
CurrencyMap = new TreeMap<>(); creates a TreeMap that will keep currencies sorted by their natural order.

HashMap in Java

It allows null values and one null key.
ProductMap.put(null, This product has no ID); stores a product with a null ID in a HashMap.

TreeMap in Java

Supports navigable map operations, allowing for retrieval of specific slices of the map.
SubMap = capitalTreeMap.headMap(M); retrieves a view of all capitals up to M in a TreeMap.

Common Curiosities

How does HashMap handle collisions?

HashMap uses linked lists or balanced trees at each index for collision resolution.

Can a HashMap contain duplicate keys?

No, HashMap cannot contain duplicate keys.

What is a TreeMap in Java?

A map implementation that stores key-value pairs sorted by their key's natural order or by a Comparator.

Can a TreeMap contain duplicate keys?

No, TreeMap also cannot contain duplicate keys.

Is TreeMap synchronized?

No, TreeMap is not synchronized by default.

Is HashMap ordered?

No, HashMap does not maintain any order of its elements.

What interfaces do HashMap and TreeMap implement?

Both implement the Map interface, but TreeMap also implements NavigableMap.

When should I use a TreeMap over a HashMap?

Use TreeMap when you need to maintain natural ordering of keys.

What is a HashMap in Java?

A data structure that stores key-value pairs in a hash table, allowing fast retrieval.

How does TreeMap maintain order?

TreeMap uses a red-black tree structure to maintain keys in sorted order.

Can I make a HashMap synchronized?

Yes, wrap it with Collections.synchronizedMap.

Can I store a null key in a HashMap?

Yes, you can store one null key in a HashMap.

How do I iterate over a TreeMap?

You can iterate over a TreeMap using entrySet, keySet, or values just like in HashMap.

When should I use a HashMap over a TreeMap?

Use HashMap when you need faster access and insertion and do not need ordering.

Can I store a null key in a TreeMap?

No, TreeMap does not allow null keys.

Share Your Discovery

Share via Social Media
Embed This Content
Embed Code
Share Directly via Messenger
Link
Previous Comparison
14k Gold vs. 18k Gold

Author Spotlight

Written by
Tayyaba Rehman
Tayyaba Rehman is a distinguished writer, currently serving as a primary contributor to askdifference.com. As a researcher in semantics and etymology, Tayyaba's passion for the complexity of languages and their distinctions has found a perfect home on the platform. Tayyaba delves into the intricacies of language, distinguishing between commonly confused words and phrases, thereby providing clarity for readers worldwide.

Popular Comparisons

Trending Comparisons

New Comparisons

Trending Terms