First consider about the LinkedHashMap. It extends the HashMap. This is the Hash table and linked list implementation of the Map interface. One difference between HashTable and LinkedHashMap is this stores data using doubly linked lists.LinkedHashMap stores data as key and value pairs.And another important thing about LinkedHashMap is it maintains the insertion order.Further it cannot have duplicate keys.But it can have any number of duplicate values.If we insert duplicate keys into a LinkedHashMap it will overwrite previous value with the same key. By referring below code segment we can get an idea about how LInkedHashMap works.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapEx {
public static void main(String[] args) {
LinkedHashMap myMap= new LinkedHashMap();
myMap.put(1,"hasitha");
myMap.put(2, "kasun");
myMap.put(3, "amal");
myMap.put(4, "hasitha");
myMap.put(5, "sumudu");
for (Map.Entry entry : myMap.entrySet()) {
System.out.println(entry.getValue());
}
}
}
Now consider about the TreeMap. This is another one implementation of Map interface. One of the most important point about TreeMap is, it maintains the natural order of keys.Further even though HashMap and LinkedHashMap can contains null keys , TreeMap cannot contain null keys.Anyhow TreeMap can contains duplicate values as HashMap and LinkedHash map. Now the tome to move for a coding example and see how TreeMap works.
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
TreeMap treeMap= new TreeMap();
treeMap.put("name", "hasitha");
treeMap.put("village", "matara");
treeMap.put("school;", "mcc");
treeMap.put("university", "ucsc");
treeMap.put("job","ASE" );
treeMap.put("sex", "male");
for(Map.Entry entry : treeMap.entrySet()) {
System.out.println(entry.getValue());
}
}
Output of above code as below.
ASE
hasitha
mcc
male
ucsc
matara
So we can see that values have been sorted according to the ascending order of the keys.
No comments:
Post a Comment