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 allowed | Uses a combination of (hash table + LinkedList) to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed | Uses 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 order | While iterating LinkedHashMap, we will get items as per insertion order | While 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 version | This is introduced in Java 1.4 version | This 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 key | Key: Allows NULL insertion but a maximum of only one NULL value: No upper limit for NULL values against any unique key | Key: From Java 1.7 version, NULL 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 |