In this article, we will discuss LinkedHashMap class – one of the Map implemented classes in detail
1. Key points about LinkedHashMap:
- LinkedHashMap is exactly same as that of HashMap
- but preserves insertion-order
- whereas HashMap stores entries in random-order
2. LinkedHashMap:
- LinkedHashMap is implementation class of Map interface (i.e.; LinkedHashMap implements Map)
- This is introduced in Java 1.4 version
- LinkedHashMap uses combination of LinkedList & hashtable to store Map entries (i.e.; key-value pairs)
- LinkedHashMap allows only unique keys but there is no restriction on values which can be duplicated
- At any time, LinkedHashMap contains only unique keys
- Insertion-order is maintained
- While iterating through LinkedHashMap, we will get map entries as per insertion-order
- Allows NULL insertion for key but maximum of only one
- Also, allows NULL insertion for values without any upper limit i.e.; we can insert null value against any unique key
- Without generics, LinkedHashMap allows to insert any type of Key/Values;
- With generics, it is type-bounded except, if we take both key-value as Objects within angle brackets
- LinkedHashMap is non-synchronized
- Present in java.util package and extends java.util.HashMap implements java.util.Map interface
- Also, implements java.lang.Cloneable, java.io.Serializable marker interfaces which provides special ability to LinkedHashMap (provided by JVM at run time) like,
- java.lang.Cloneable: to create a duplicate object or to clone an object
- java.io.Serializable: to transfer objects across network
Source: Team BenchResources.Net
3. LinkedHashMap constructors:
3.1 LinkedHashMap hs = new LinkedHashMap();
- creates an empty LinkedHashMap object of size 16
- with default fill ratio 0.75
3.2 LinkedHashMap hs = new LinkedHashMap(int initialCapacity);
- creates an empty LinkedHashMap object of specified size (or initial capacity)
- with default fill ratio 0.75
3.3 LinkedHashMap hs = new LinkedHashMap(int initialCapacity, float loadFactor);
- creates an empty LinkedHashMap object of specified size (or initial capacity)
- with specified fill ratio (for example 0.85)
3.4 LinkedHashMap hs = new LinkedHashMap(Collection c);
- created an equivalent LinkedHashMap object for the specified collection
- it is basically used for inter-conversion between collection objects
3.5 LinkedHashMap hs = new LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder);
- creates an empty LinkedHashMap object of specified size (or initial capacity)
- with specified fill ratio (for example 0.85)
- along with specified ordering mode like true for access-order and false for insertion-order
4. Fill ratio (or Load factor)
- Fill ratio is also known as Load factor
- This factor determines when to increase the size of LinkedHashMap automatically
- For example, for the 1st two constructors the default load factor is 75 à which means after filling 75 % of LinkedHashMap, new LinkedHashMap of bigger size will be created
- For 3rd constructor, programmer can define load factor while creating LinkedHashMap object. If programmer define it to be 0.95, then after filling 95% of LinkedHashMap, size of LinkedHashMap will be increased automatically
- The value of Load factor should be in between 0 to 1.0
LinkedHashMapAddAndRemove.java
package in.bench.resources.java.collection;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class LinkedHashMapAddAndRemove {
public static void main(String[] args) {
// creating LinkedHashMap object of type <Integer, String>
LinkedHashMap<Integer, String> lhm =
new LinkedHashMap<Integer, String>();
// adding key-value pairs to LinkedHashMap object
lhm.put(1, "Google");
lhm.put(2, "Facebook");
lhm.put(3, "Yahoo");
lhm.put(4, "Amazon");
lhm.put(5, "Reddit");
System.out.println("Printing all"
+ " key-value pairs inside {}\n" + lhm + "\n");
System.out.println("\nIterating using keySet\n");
// Iterating key-pairs using keySet
Set<Integer> keys = lhm.keySet();
for(Integer key : keys) {
System.out.println(key + " " + lhm.get(key));
}
System.out.println("\n\nIterating using Map Entry interface\n");
// Iterating key-pairs using Map entry
Set set = lhm.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry)iterator.next();
System.out.println(mapEntry.getKey() + " "
+ mapEntry.getValue());
}
// removing map entry at 4th position
System.out.println("\n\nEntry removed at 4th position : "
+ lhm.remove(4));
}
}
Output:
Printing all key-value pairs inside {}
{1=Google, 2=Facebook, 3=Yahoo, 4=Amazon, 5=Reddit}
Iterating using keySet
1 Google
2 Facebook
3 Yahoo
4 Amazon
5 Reddit
Iterating using Map Entry interface
1 Google
2 Facebook
3 Yahoo
4 Amazon
5 Reddit
Entry removed at 4th position : Amazon
5. Difference between HashMap and LinkedHashMap ?
- The main difference between HashMap and LinkedHashMap is insertion-order
- HashMap doesn’t maintain insertion-order and print values in random-order while iterating
- whereas LinkedHashMap maintains insertion-order as seen in above example
- Note: All methods of LinkedHashMap is non-synchronized
Q) How to make LinkedHashMap synchronized ?
- It can be easily converted into synchronized LinkedHashMap
- Using utility method synchronizedMap(lhm); of java.util.Collections class
Map map = Collections.synchronizedMap(lhm);
Related Articles:
- How to get all keys of a HashMap
- How to get all values of a HashMap
- How to get all Entries or Key-Value pairs of HashMap
- How to get size or length of HashMap
- How to check whether a particular key is present in HashMap
- How to check whether a particular value is present in HashMap
- How to check whether HashMap is empty or not ?
- Adding one HashMap to another HashMap using putAll method
- How to delete an entry of HashMap
- How to delete all entries of HashMap
- How to remove an entry from HashMap by comparing values in Java 8
- How to remove an entry from HashMap by comparing keys in Java 8
- Various ways to iterate through HashMap
- To reverse order the LinkedHashMap contents
- Map: How ConcurrentModificationException can be handled in Java
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html
Happy Coding !!
Happy Learning !!