Core Java Tutorial

Core Java Tutorial

Comparison on HashMap TreeMap and LinkedHashMap

Comparison on HashMap, TreeMap, LinkedHashMap:

HashMapTreeMapLinkedHashMap
No Duplicate Key are allowed, But values can be anything.No Duplicate Key are allowed, But values can be anything.No Duplicate Key are allowed, But values can be anything.
Orders cannot be predicted, in can print the data in any orderTreeMap will follow the natural ordering of key, All Keys in the TreeMap should be in same typeLinkedHashMap insertion order will be maintained, Adding duplicate key will not affect the existing order.
Supports 1 null KeyDoes not support null key elementsSupports 1 null elements
Gives good performance on read and writeSlow when compared with HashMap, use this only when you need ordering by defaultSlow when compared with HashMap, but faster than TreeMap, Use this if you need to maintain the insertion order of the data.

Example:

package com.candidjava.core;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class MapComparison {
  public static void main(String[] args) {
    HashMap<String, String> hm=new HashMap<String, String>();
    hm.put("name","candid");
    hm.put("email","candid@gmail.com");
    hm.put("password", "123456");
    hm.put("street", "shanthi nagar");
    hm.put("password", "789");
    hm.put("altemail", null);
    hm.put("altph", null);
    
    TreeMap<String, String> tm=new TreeMap<String, String>();
    tm.putAll(hm);
    LinkedHashMap<String, String> lhm=new LinkedHashMap<String, String>();
    lhm.putAll(hm);
    
    System.out.println("HashMap:  " + hm);
    System.out.println("TreeMap:  " + tm);
    System.out.println("LinkedHashMap:  " + lhm);
  }
}
Output:
HashMap:  {password=789, altemail=null, street=shanthi nagar, name=candid, altph=null, email=candid@gmail.com}
TreeMap:  {altemail=null, altph=null, email=candid@gmail.com, name=candid, password=789, street=shanthi nagar}
LinkedHashMap:  {password=789, altemail=null, street=shanthi nagar, name=candid, altph=null, email=candid@gmail.com}