What is the difference between HashMap
, LinkedHashMap
and TreeMap
in Java?
I don\'t see any difference in the output as all the three
The most important among all the three is how they save the order of the entries.
HashMap
- Does not save the order of the entries.
eg.
public static void main(String[] args){
HashMap hashMap = new HashMap<>();
hashMap.put("First",1);// First ---> 1 is put first in the map
hashMap.put("Second",2);//Second ---> 2 is put second in the map
hashMap.put("Third",3); // Third--->3 is put third in the map
for(Map.Entry entry : hashMap.entrySet())
{
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
}
LinkedHashMap
: It save the order in which entries were made. eg:
public static void main(String[] args){
LinkedHashMap linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("First",1);// First ---> 1 is put first in the map
linkedHashMap.put("Second",2);//Second ---> 2 is put second in the map
linkedHashMap.put("Third",3); // Third--->3 is put third in the map
for(Map.Entry entry : linkedHashMap.entrySet())
{
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
}
TreeMap
: It saves the entries in ascending order of the keys. eg:
public static void main(String[] args) throws IOException {
TreeMap treeMap = new TreeMap<>();
treeMap.put("A",1);// A---> 1 is put first in the map
treeMap.put("C",2);//C---> 2 is put second in the map
treeMap.put("B",3); //B--->3 is put third in the map
for(Map.Entry entry : treeMap.entrySet())
{
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
}