HashMap, TreeMap and LinkedHashMap difference

Difference

  1. HashMap and LinkedHashMap contains data in key value pair. TreeMap also contains data in key value pair but it is sorted according to natural ordering (ascending order).

    Map<Integer, String> codeCityHashMap = new HashMap<Integer, String>();
    codeCityHashMap.put(11, "Delhi");
    codeCityHashMap.put(22, "Mumbai");
    codeCityHashMap.put(33, "Kolkata");
    codeCityHashMap.put(44, "Chennai");

    Map<Integer, String> codeCityLinkedHashMap = new LinkedHashMap<Integer, String>();
    codeCityLinkedHashMap.put(11, "Delhi");
    codeCityLinkedHashMap.put(22, "Mumbai");
    codeCityLinkedHashMap.put(33, "Kolkata");
    codeCityLinkedHashMap.put(44, "Chennai");

    Map<Integer, String> codeCityTreeMap = new TreeMap<Integer, String>();
    codeCityTreeMap.put(44, "Chennai");
    codeCityTreeMap.put(11, "Delhi");
    codeCityTreeMap.put(33, "Kolkata");
    codeCityTreeMap.put(22, "Mumbai");

  2. If you know the key then you can get the value in HashMap, LinkedHashMap and TreeMap.
  3. HashMap, LinkedHashMap and TreeMap doesn't allow duplicate keys but allows duplicate values, means two different keys can have same values. But two different values can't have same key.

    codeCityHashMap.put(22, "Pune");
    System.out.println(codeCityHashMap);
    Output: {33=Kolkata, 22=Pune, 11=Delhi, 44=Chennai}
    //Mumbai is replaced with Pune for 22

    codeCityLinkedHashMap.put(22, "Pune");
    System.out.println(codeCityLinkedHashMap);
    Output: {33=Kolkata, 22=Pune, 11=Delhi, 44=Chennai}
    //Mumbai is replaced with Pune for 22

    codeCityTreeMap.put(22, "Pune");
    System.out.println(codeCityTreeMap);
    Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai}
    //Mumbai is replaced with Pune for 22

  4. HashMap and LinkedHashMap allows only one null value as a key. TreeMap doesn't allow null value as a key. It throws NullPointerException. Though multiple keys can have null values in any of these three collections.

    codeCityHashMap.put(null, "Ratlam");
    codeCityHashMap.put(null, "Bangalore");
    codeCityHashMap.put(55, null);
    System.out.println(codeCityHashMap);
    Output: {33=Kolkata, 22=Pune, 55=null, 11=Delhi, 44=Chennai, null=Bangalore}

  5. HashMap doesn't maintain insertion order. LinkedHashMap maintains an insertion order. TreeMap maintains a natural order i.e. ascending order.

    System.out.println(codeCityHashMap);
    Output: {33=Kolkata, 22=Pune, 55=null, 11=Delhi, 44=Chennai, null=Bangalore}

    System.out.println(codeCityLinkedHashMap);
    Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai, null=Bangalore}
    System.out.println(codeCityTreeMap);
    Output: {11=Delhi, 22=Pune, 33=Kolkata, 44=Chennai}

  6. HashMap and LinkedHashMap implements Map interface but TreeMap implements Map, SortedMap and NavigableMap.

Comments

Popular posts from this blog

Collections in Java

Exception Handling

OOPS Concept in Java