Difference Between TreeMap VS HashMap VS LinkedHashMap In Java

In this article, we will compare important implementation classes of Map i.e.; HashMap v/s LinkedHashMap v/s TreeMap

So lets us discuss in tabular format;

HashMap vs LinkedHashMap vs TreeMap

HashMap LinkedHashMap TreeMap
Uses a hash table to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowedUses a combination of (hash table + LinkedList) to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowedUses the Red-Black tree to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed
Insertion order is NOT maintained, as it uses a hashing technique to store key-value pairs (i.e.; map entries)Insertion order is maintained, as it uses the doubly-linked list to store key-value pairs (i.e.; map entries)Insertion order is NOT maintained, as key-value pairs (i.e.; map entries) are stored according to some sorting order
HashMap doesn’t deal with  sorting order; but it can be converted to TreeMap to store key-value pairs (i.e.; map entries) in some sorting orderTreeMap ts = new TreeMap(hashMap);LinkedHashMap doesn’t deal with  sorting order; but it can be converted to TreeMap to store key-value pairs(i.e.; map entries) in some sorting orderTreeMap ts = new TreeMap(linkedHashMap);Keys in TreeMap are sorted, according to some sorting order; it could be either default natural sorting order or programmer-defined customized sorting order
While iterating HashMap, we will get items in random orderWhile iterating LinkedHashMap, we will get items as per insertion orderWhile iterating TreeMap, we will get items in sorted order;  either natural ordering or customized sorting order
This is introduced in the original collection framework in Java 1.2 versionThis is introduced in Java 1.4 versionThis is also introduced in the original collection framework in Java 1.2 version
Key: Allows NULL insertion but a maximum of only one NULL value: No upper limit for NULL values against any unique keyKey: Allows NULL insertion but a maximum of only one NULL value: No upper limit for NULL values against any unique keyKey: From Java 1.7 versionNULL is not allowed to insert;
But with Java version less than 1.6, only as 1st element allowed (for keys)Value: No upper limit for NULL values against any unique key

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment