LinkedHashMap overview
LinkedHashMap is based on HashTable and LinkedList implementation
Main features of LinkedHashMap
It also stores elements in the key-value pair like any other Map
It maintains the Insertion order of elements
It can have Null Key and Null Values
Value can be retrieved by passing key
If passed key is not exist in the Map then value returned will be Null
LinkedHashMap can be created using constructor as below
- LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();
LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();
Important methods in LinkedHashMap
put(Object key, Object value)
This method stores the specified value and associates it with the specified key in this map.
get(Object key)
This method will return the value associated with a specified key in this map.
We can add key value pair as below
- lhm.put(1,”one”);
lhm.put(1,”one”);
We can retrieve value for the specific key as
- lhm.get(1);
lhm.get(1);
Example
- import java.util.*;
- public class LinkedHashMapExample {
- public static void main(String args[]) {
- LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>();
- lhm.put(1, "One");
- lhm.put(2, "Two");
- lhm.put(3, "Three");
- lhm.put(4, "Four");
- lhm.put(5, "Five");
- System.out.println(lhm);
- System.out.println("Value for the key 1 is "+lhm.get(1));
- System.out.println("Value for the key 10 is "+lhm.get(10));
- }
- }
import java.util.*; public class LinkedHashMapExample { public static void main(String args[]) { LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>(); lhm.put(1, "One"); lhm.put(2, "Two"); lhm.put(3, "Three"); lhm.put(4, "Four"); lhm.put(5, "Five"); System.out.println(lhm); System.out.println("Value for the key 1 is "+lhm.get(1)); System.out.println("Value for the key 10 is "+lhm.get(10)); } }
Note : We can see that corresponding value for existing key is retrieved and value for non-existing key is returned as Null
When to use LinkedHashMap ?
Whenever we want to store data in key-value pair format and Whenever we need to maintain the order of insertion
When not to use LinkedHashMap ?
Whenever we don’t want to store key-vallue pair data and whenever we don’t worry about the order of insertion