HashMap vs. TreeMap in Java

The difference between HashMap and TreeMap in java is that HashMap is implemented by using a Hash table whereas TreeMap is implemented by using a red-black tree.

Advertisement - Continue Reading Below
HashMap vs. TreeMap in Java

HashMap and TreeMap in java, both implement maps and same functions, but the implementation of both HashMap and TreeMaps is different. The difference between HashMap and TreeMap is the iteration through the entries. TreeMap is a sortedMap; TreeMap is implemented by using Red-black tree. Elements in TreeMap is in order whereas there is no order of elements in HashMap. The following code will make the difference between HashMap and TreeMap in Java very clear.

Contents: Difference between HashMap and TreeMap in Java

Comparison Chart

BasisHashMapTreeMap
MeaningHashMap is implemented by using Hash table

TreeMap is implemented by using red-black tree.

 

SortingElements are not sorted in HashMapElements are sorted in TreeMap
Time ComplexityTime complexity of HashMap is O(1).Time complexity of TreeMap is O(log(n))
Null ValuesNull values are  allowed in HashMapNull values are allowed in TreeMap
Advertisement - Continue Reading Below

 HashMap

HashMap in Java is a collection of class that is used to make a map. HashMap store keys and values like < Key, Value>. There is no order in HashMap. HashMap in java is very similar to a hash table. The order in which the keys and values are added to hashmap the return order of keys and values is not the same. HashMap does not store keys and values in sorted order. If we need to use all the methods and functions of hashMap, we must include java.util.HashMap.

TreeMap

In java, TreeMap is used to implement map using a tree. TreeMap is used to store keys and values as a pair, and above all, it stores keys and values in sorted order. In treeMap values are based on keys. TreeMap implements NavigableMap interface. TreeMap contains only unique class elements. HashMaps cannot have null values stored, but TreeMap can have null values stored.

Advertisement - Continue Reading Below

Key Differences

  1. HashMap is implemented by using Hash table whereas TreeMap is implemented by using red-black tree.
  2. Elements are not sorted in HashMap whereas Elements are sorted in TreeMap
  3. The time complexity of HashMap is O(1) whereas Time complexity of TreeMap is O(log(n)).
  4. Null values are allowed in HashMap whereas Null values are allowed in TreeMap

Conclusion

In this article above we see the clear difference between hashMaps and TreeMaps with examples.

Explanatory Video

Leave a Comment