HashMap vs. TreeMap in Java

HashMap and TreeMap both store values in the form of key-value pairs. There are built-in classes, in Java, for both of them.

Similarities

First, let’s take a brief look at the similarities between them:

  1. Manual synchronization​ is required for multi-threaded usage.
  2. Both use an Iterator for traversal.
  3. First incorporated in Java Development Kit 1.2.

Differences

The following are the differences between the two classes:

HashMap

  • Allows one null as a key and multiple nulls as values

  • No iteration order


  • Insertion/deletion requires O(1) time



  • Implements the Map interface

TreeMap

  • Nulls are only allowed as values


  • Iterates in the natural order or the order provided by the Comparator

  • Insertion/deletion requires O(log n) time, where n is the number of elements in the TreeMap

  • Implements NavigableMap interface

Hierarchy

Class diagram showing a part of the hierarchy
Class diagram showing a part of the hierarchy

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved