- LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
- LinkedHashMap is a Hash table and linked list implementation of the Map interface
- LinkedHashMap contains only unique elements.
- LinkedHashMap may have one null key and multiple null values.
- LinkedHashMap is same as HashMap instead maintains insertion order.
- LinkedHashMap maintains a doubly-linked list running through all of its entries
Example of LinkedHashMap
- import java.util.*;
- class LinkedHashMapDemo
{
- public static void main(String args[]){
- LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
- hm.put(100,“A”);
- hm.put(101,“B”);
- hm.put(102,“C”);
- for(Map.Entry m:hm.entrySet()){
- System.out.println(m.getKey()+” “+m.getValue());
- }
- }
- Output:
100 A
101 B
103 C
Another Example of LinkedHashMap
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class LinkedHashMapDemo1 {
public static void main(String args[]) {
// HashMap Declaration
LinkedHashMap<Integer, String> lhm =
new LinkedHashMap<Integer, String>();
//Adding elements to LinkedHashMap
lhm.put(22, "A");
lhm.put(33, "B");
lhm.put(1, "C");
lhm.put(2, "D");
lhm.put(100, "E");
// Generating a Set of entries
Set set = lhm.entrySet();
// Displaying elements of LinkedHashMap
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print("Key is: "+ me.getKey() +
"& Value is: "+me.getValue()+"\n");
}
}
}
Output:
Key is: 22& Value is: A
Key is: 33& Value is: B
Key is: 1& Value is: C
Key is: 2& Value is: D
Key is: 100& Value is: E