This Tutorial Explains all about LinkedHashMap in Java Including LinkedHashMap Example & Methods, Implementation in Java, LinkedHashMap vs HashMap:
LinkedHashMap in Java is an implementation that combines HashTable and LinkedList implementation. It implements the Map interface. The key-value pairs of LinkedHashMap have a predictable order of iteration.
In addition to Map interface, LinkedHashMap also extends the HashMap class.
=> Visit Here To See The Java Training Series For All.
Table of Contents:
LinkedHashMap In Java
Some of the main characteristics of LinkedHashMap are:
- It contains key-based values.
- Maintains the order of the insertion of key-value pairs.
- It does not allow duplicates, it has unique elements.
- It can have a single null key. But it allows multiple null values.
- Java LinkedHashMap is not synchronized.
Declaration Of LinkedHashMap
The LinkedHashMap class in Java is a part of java.util package.
The general declaration of this class in Java is as follows:
public class LinkedHashMap<K, V> extends HashMap<K, V> implements Map<K, V>
Here K=> type of keys in the map.
V=> type of values mapped to keys.
The class hierarchy of LinkedHashMap is shown below:
As shown in the above diagram, LinkedHashMap inherits HashMap and AbstractMap class and implements the Map interface.
LinkedHashMap Example
Given below is a simple example.
import java.util.*; class Main{ public static void main(String args[]){ //declare and initialize LinkedHashMap LinkedHashMap<Integer,String> num_map=new LinkedHashMap<Integer,String>(); num_map.put(1,"ONE"); num_map.put(2,"TWO"); num_map.put(3,"THREE"); num_map.put(4,"FOUR"); num_map.put(5,"FIVE"); System.out.println("The contents of LinkedHashMap:"); //retrieve the key-value pairs as set using entrySet & print each entry for(Map.Entry m:num_map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
Output:
The contents of LinkedHashMap:
1 ONE
2 TWO
3 THREE
4 FOUR
5 FIVE
Constructors And Methods
Let’s discuss the constructors and methods provided by LinkedHashMap class. First, we will discuss the constructors followed by methods.
Constructors
Constructor Prototype | Description |
---|---|
LinkedHashMap() | Default constructor for LinkedHashMap. |
LinkedHashMap(int capacity) | Creates a LinkedHashMap object with a given capacity. |
LinkedHashMap(int capacity, float loadFactor) | Creates a LinkedHashMap object with given capacity and loadFactor. |
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) | Creates a LinkedHashMap object with a given capacity and loadFactor. Also, the ordering mode (accessOrder) is specified. |
LinkedHashMap(Map m) | Creates a LinkedHashMap object and initializes it with the values from the map m passed as an argument. |
Methods
Method | Method Prototype | Description |
---|---|---|
get | V get (Object key) | Returns the value for the given key. |
clear | void clear () | Clears all key-value pairs in the map. |
containsValue | boolean containsValue (Object value) | Checks if the map contains one or more keys mapped to the given value. Returns true if yes. |
entrySet | Set < Map.Entry < K,V > > entrySet() | Returns set of entries in the map. |
forEach | void forEach (BiConsumer < ? super K, ? super V > action) | Executes the given action for all entries in the map. |
getOrDefault | V getOrDefault (Object key, V defaultValue) | Returns the value mapped to the key. If no value is mapped, default is returned. |
keySet | Set < K > keySet () | Returns set of keys in the map. |
removeEldestEntry | protected boolean removeEldestEntry ( Map.Entry < K,V > eldest ) | Removes eldest entry in the map and returns true on removal. |
replaceAll | void replaceAll ( BiFunction < ? super K, ? super V, ? extends V > function ) | Invokes the given function on each entry and replaces the result of the function with the values. |
values | Collection < V > values () | Returns the collection of values in the map. |
Implementation In Java
The Java program below shows the implementation of LinkedHashMap by demonstrating the methods discussed above.
import java.util.*; public class Main { public static void main(String a[]) { //declare LinkedHashMap and initialize it with values LinkedHashMap<String, String> colors_map = new LinkedHashMap<String, String>(); colors_map.put("one", "Red"); colors_map.put("two", "Green"); colors_map.put("three", "Blue"); // Original LinkedHashMap System.out.println("Original LinkedHashMap:" + colors_map); //isEmpty () System.out.println("LinkedHashMap 'colors_map' empty?:" + colors_map.isEmpty()); //size () System.out.println("Size of the map: " + colors_map.size()); //get () System.out.println("Value for key = 'one':" + colors_map.get("one")); //containsKey () System.out.println("colors_map contains key = 'two':"+ colors_map.containsKey("two")); //containsValue () System.out.println("colors_map contains value 'ree':" + colors_map.containsValue("ree")); //remove () System.out.println("delete element 'one': " + colors_map.remove("one")); System.out.println("Updated colors_map:" + colors_map); } }
Output:
Original LinkedHashMap:{one=Red, two=Green, three=Blue}
LinkedHashMap ‘colors_map’ empty?:false
Size of the map: 3
Value for key = ‘one’:Red
colors_map contains key = ‘two’:true
colors_map contains value ‘ree’:false
delete element ‘one’: Red
Updated colors_map:{two=Green, three=Blue}
In this program, we declare a color map and initialize it. Then we use the various methods discussed above to get the results.
LinkedHashMap Vs HashMap
LinkedHashMap | HashMap |
---|---|
Implements ordered maps. | Implements unordered maps. |
Uses doubly linked-list of buckets. | Uses hash table. |
Maintains order when iterating the elements. | Does not maintain the order when iterating. |
Requires more memory. | Requires less memory than LinkedHashMap. |
Basic operations like adding, removing, searching, etc are slower. | Basic operations like adding, removing searching are faster. |
HashMap Vs TreeMap Vs LinkedHashMap
Let’s now compare the three map implementations viz. HashMap, TreeMap, and LinkedHashMap.
The following table shows the comparison/difference.
Comparison Parameter | HashMap | LinkedHashMap | TreeMap |
---|---|---|---|
Interface | Map | Map | Map, SortedMap, NavigableMap |
Data structure | List of buckets | Double linked-list of buckets | Red-Black tree |
Iteration Order | No ordering maintained. | Sorted as per insertion order | Sorted according to the natural ordering of elements |
Null Keys | Are allowed | Are allowed | Not allowed |
Synchronization | Not synchronized | Not synchronized | Not synchronized |
Keys requirement | Need to overwrite equals () and hashCode () methods | Need to overwrite equals () and hashCode () methods | Natural ordering is maintained or comparator needs to be supplied |
The time complexity of basic operations | O (1) | O (1) | O (1) |
Frequently Asked Questions
Q #1) What is LinkedHashMap in Java?
Answer: LinkedHashMap in Java is implemented as a combination of the HashTable and LinkedList. It implements the map interface. It has a predictable iteration order. It internally uses a doubly-linked list for entries.
Q #2) How does LinkedHashMap work in Java?
Answer: It is similar to HashMap but differs from HashMap in the order of insertion that the LinkedHashMap maintains. The elements in the LinkedHashMap are stored in the same way as they are entered in the data structure.
Q #3) How do I loop through a LinkedHashMap?
Answer: We can loop through a LinkedHashMap using an iterator.
Following are the steps that we can follow to iterate through the LinkedHashMap using iterator:
- Create a new LinkedHashMap object.
- Use Put API method to insert key-value pairs in the map.
- Call entrySet () API method to obtain a set of key-value pairs in the map.
- Invoke iterator on this set to retrieve each key-value pair using getKey () and getValue () API methods.
Q #4) What is the use of LinkedHashMap in Java?
Answer: The main use of LinkedHashMap in Java is to use it for preserving the insertion order. It can also be used to preserve the access order using which the keys are accessed. Since it is faster than HashMap, LinkedHashMap can be used in place of HashMap where the performance is critical.
Q #5) Is HashMap faster than LinkedHashMap?
Answer: Both are similar in performance. HashMap needs less memory when compared to LinkedHashMap as HashMap does not maintain the accessing order. Thus comparatively HashMap is faster.
Conclusion
In this tutorial, we have discussed the LinkedHashMap in Java. We have seen the details regarding class declaration, class hierarchy, constructors, and methods.
We have also learned the primary differences between, LinkedHashMap and HashMap. We also discussed the 3-way difference between LinkedHashMap, HashMap, and TreeMap.
In our upcoming tutorial, we will explore more topics on Java Collection Framework.
=> Watch Out The Simple Java Training Series Here.