English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

differences between TreeMap, HashMap, and LinkedHashMap in Java programming

HashMap, TreeMap, and LinkedHashMap all implement the java.util.Map interface, and the following are their features.

Hash map

  • The insertion and lookup complexity of HashMap is O(1).

  • HashMap allows one null key and multiple null values.

  • HashMap does not maintain any order.

Tree diagram

  • The insertion and lookup complexity of TreeMap is O(logN).

  • TreeMap does not allow null keys, but allows multiple null values.

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

LinkedHashMap

  • The insertion and lookup complexity of LinkedHashMap is O(1).

  • LinkedHashMap allows one null key and multiple null values.

  • LinkedHashMap maintains the order of insertion of key-value pairs.

Example

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: 
" + );
      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: 
" + 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: 
" + map2);
   }
}

Output Result

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 can see that HashMap has a random key order, LinkedHashMap retains the order of inserted keys, and TreeMap has a sorted key order.