Main differences between a HashMap and a TreeMap in Java are:
1. Order: A HashMap does not maintain any order of its keys.
In a HashMap there is no guarantee that the element
inserted first will be retrieved first.
2. In a TreeMap elements are stored according to natural
ordering of elements. A TreeMap uses compareTo()
method to store elements in a natural order.
3. Internal Implementation: A HashMap uses Hashing
internally. A TreeMap internally uses Red-Black tree
implementation.
4. Parent Interfaces: A HashMap implements Map interface.
TreeMap implements NavigableMap interface.
5. Null values: A HashMap can store one null key and
multiple null values. A TreeMap can not contain null key
but it may contain multiple null values.
6. Performance: A HashMap gives constant time performance
for operations like get() and put(). A TreeMap gives order
of log(n) time performance for get() and put() methods.
7. Comparison: A HashMap uses equals() method to compare
keys. A TreeMap uses compareTo() method for
maintaining natural ordering.
8. Features: A TreeMap has more features than a HashMap. It
has methods like pollFirstEntry() , pollLastEntry() ,
tailMap() , firstKey() , lastKey() etc. that are not provided
by a HashMap
javatpoint.com/difference-between-hashmap-and-treemap#:~:text=HashMap%20allows%20a%20single%20null,can%20have%20multiple%20null%20values.&text=HashMap%20allows%20heterogeneous%20elements%20because,a%20key%20because%20of%20sorting.