Difference between TreeMap, HashMap and LinkedHashMap in Java programming

Java 8Object Oriented ProgrammingProgramming

HashMap, TreeMap and LinkedHashMap all implements java.util.Map interface and following are their characteristics.

HashMap

  • HashMap has complexity of O(1) for insertion and lookup.

  • HashMap allows one null key and multiple null values.

  • HashMap does not maintain any order.

TreeMap

  • TreeMap has complexity of O(logN) for insertion and lookup.

  • TreeMap does not allow null key but allow multiple null values.

  • TreeMap maintains order. It stores keys in sorted and ascending order.

LinkedHashMap

  • LinkedHashMap has complexity of O(1) for insertion and lookup.

  • LinkedHashMap allows one null key and multiple null values.

  • LinkedHashMap maintains order in which key-value pairs are inserted.

Example

 Live Demo

import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class Tester {
   public static void main(String args[]) {
      Map<String, String> map = new HashMap<String, String>();
      map.put("One", "1");
      map.put("Five", "5");
      map.put("Four", "4");
      map.put("Two", "2");
      map.put("Three", "3");
      System.out.println("HashMap: \n" + map);
      Map<String, String> map1 = new LinkedHashMap<String, String>();
      map1.put("One", "1");
      map1.put("Five", "5");
      map1.put("Four", "4");
      map1.put("Two", "2");
      map1.put("Three", "3");
      System.out.println("LinkedHashMap: \n" + map1);
      Map<String, String> map2 = new TreeMap<String, String>();
      map2.put("One", "1");
      map2.put("Five", "5");
      map2.put("Four", "4");
      map2.put("Two", "2");
      map2.put("Three", "3");
      System.out.println("TreeMap: \n" + map2);
   }
}

Output

HashMap:
{Five=5, One=1, Four=4, Two=2, Three=3}
LinkedHashMap:
{One=1, Five=5, Four=4, Two=2, Three=3}
TreeMap:
{Five=5, Four=4, One=1, Three=3, Two=2}

Here you see, HashMap has random order of Keys, LinkedHashMap has preserved the order in which keys are inserted and TreeMap has sorted order of keys.

raja
Published on 01-Nov-2018 12:07:33
Advertisements