In this article, we will discuss difference between HashMap and LinkedHashMap classes in detail i.e.; HashMap vs LinkedHashMap
Lets us move on and discuss key differences between these 2 Map implemented classes
HashMap v/s LinkedHashMap
|Uses hash table to store map entries (i.e.; key-value pairs)||Uses combination of hash table + LinkedList to store map entries (i.e.; key-value pairs)|
|Doesn’t maintain insertion order i.e.; while iterating through HashMap, we will get map entries in random order||Since, it uses doubly-linked list to store map entries (i.e.; key-value pairs), maintains insertion order|
|This is introduced in the original collection framework in Java 1.2 version||This is introduced in Java 1.4 version|
When to use HashMap?
- HashMap stores key-value pairs which uses hashing technique to store key-value pairs
- So, search operation is faster
- So, if business requirement is to store key-value pairs for faster search operation or more number of search operation on the baisis of keys; without concerning insertion order
- Then, HashMap is the very apt choice
When to use LinkedHashMap?
- This is exactly same as that of HashMap, but underlying data structure to hold key-value pairs is different
- It uses doubly-linked list which allows to hold key-value pairs as per insertion order
- So, if business requirement is to store key-value pairs for faster search operation or more number of search operation concerning/maintaining insertion order
- Then, LinkedHashSet is the very apt choice which maintains insertion order
- So while iterating through LinkedHashSet, we will get map entry (key-value pairs) as per insertion order (as against random in HashMap)
Happy Coding !!
Happy Learning !!