The Class
LinkedHashMap is an extension of
Java HashMap Implementation with specific feature of retaining the insertion order in the order, in which they were inserted. Also if one inserts the key again into the LinkedHashMap the original orders is retained.
This allows insertion-order iteration over the
Java Map Interfaces - HashMap, TreeMap, LinkedHashMap. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.
LinkedHashMap Constructors :
In addition to those methods defined by Map and HashMap, the LinkedHashMap includes these methods,
Linked Hash Map
import java.util.*;
class LinkedHashMapTest
{
public static void main(String arg[])
{
LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>();
lhm.put("Ramesh", "Intermediate");
lhm.put("Shiva", "B-Tech");
lhm.put("Santosh", "B-Com");
lhm.put("Asha", "Msc");
lhm.put("Raghu", "M-Tech");
Set set = lhm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
System.out.println("The Key Contains : " + lhm.containsKey("Shiva"));
System.out.println("The value to the corresponding to key : " + lhm.get("Asha"));
}
}
OUTPUTRamesh : Intermediate
Shiva : B-Tech
Santosh : B-Com
Asha : Msc
Raghu : M-Tech
The Key Contains : true
The value to the corresponding to key : Msc
DESCRIPTIONIn this program, LinkedHashMap
object is created of both key
and value
types are String
. Five records are inserted into the LinkedHashMap and then iterating the set LinkedHashMap using Map.Entry and printing the key and values as inserted into it.
THINGS TO TRY
- Take
LinkedHashMap
type of key String
and value of type Integer
for adding student details given below and print the LinkedHashMap
.
[Raja=50, Sareesh=45, Hemanth=40, Srinath=50]
- If you provide
key
which does not exists in LinkedHashMap
at containsKey
null
will be returned. Try for the below code.
lhm.containsKey("Raja");
- You can apply
Map
and Hash Map
methods to LinkedHashMap
.