# Difference Between HashMap and TreeMap in Java

Both HashMap and TreeMap are considered to be Map classes because they both carry out the responsibilities of the Map interface. A Map is an object that stores key-value pairs, in which there is only one instance of each key but there may be multiple instances of the value. The hash table is a type of data structure that is utilised by the HashMap class. As a form of data storage, the red-black tree is utilised by the TreeMap.

## What is a HashMap?

A HashMap uses a data structure known as the hash table in order to store the map's key-value pair. The hash code of the keys is used in the process of inserting key-value pairs into the database. Hence, each key in the map needs to be distinct from the others so that it can be used to retrieve the values.

Because the insertion order is not preserved in HashMap, the HashMap object does not return the elements in the order in which they were added to the map. On the other hand, the order in which the elements will be returned is not guaranteed to be consistent at any point.

While it is only possible for the key to be NULL once, the values can have any number of occurrences of this value. Both different types of objects for use as keys and different types of objects for use as values can be stored in a HashMap.

### How to Create a HashMap?

You can construct a HashMap using one of these four methods −

HashMap()
HashMap(Map m)
HashMap(int capacity),
HashMap(int capacity, float fillRatio)
• The initial constructor of HashMap creates an object that is empty by default.

• The second constructor uses the components of Map "m" to perform the initialization of the HashMap.

• The capacity of the HashMap is set to the value specified in the argument by the third Constructor when it is initialised.

• The capacity of the HashMap object, as well as the fill ratio, are both set to their default values by the fourth constructor.

• The HashMap has a default size of 16, and its default fill ratio is 0.75. Both of these values can be changed if necessary.

For Example

import java.util.HashMap;
public class HashMapSample {
public static void main(String[] args) {
HashMap map = new HashMap();

map.put("Today is","Monday");
map.put("Tomorrow is","Tuesday");
System.out.println(map);
}
}

It will produce the following Output

Today is = Monday
Tomorrow is =Tuesday

## What is a TreeMap?

TreeMap is another type of Map class, just like HashMap. The TreeMap class is an extension of the AbstractMap class and implements the NavigabelMap and SortedMap interfaces.

The pieces of the map are saved in a tree-like format within the TreeMap objects. The Red-Black tree is the data structure that is utilised in order to store the Map.

The key-value pair is stored in a TreeMap in the order in which it was sorted, which enables the elements to be retrieved more quickly. The elements are returned by the TreeMap object in the order that they were sorted in (which is ascending).

### How to Construct a TreeMap?

There are four different ways to construct a TreeMap −

TreeMap( )
TreeMap(Comparator<? super K> comp)
TreeMap(Map<? extends K, ? extends V> m)
TreeMap(SortedMap<K, ? extends V> sm)
• The initial constructor will generate a TreeMap object that is empty and will arrange its keys in the way that makes the most sense.

• The second constructor will generate an empty tree map, which will then be compared and ordered using the "comp" comparator.

• The third constructor described above will be responsible for creating a TreeMap, which will then have its entries initialised using those from Map "m".

• The fourth constructor will produce a TreeMap, and it will be initialised using the entries of the SortedMap object that will be passed in as a parameter.

Treemap does not contain any additional methods of its own; instead, it relies on the methods provided by the NavigableMap and SortedMap interfaces as well as the AbstractMap class.

For Example

import java.util.TreeMap;
public class TreeMapSample {
public static void main(String[] args) {
TreeMap<String,String> map= new TreeMap<String,String>();
map.put("Today is", "Monday");
map.put("Tomorrow is", "Tuesday");
System.out.println(map);
}
}

## Difference between HashMap and TreeMap

The following table highlights the major differences between HashMap and TreeMap −

Basis of comparisonHashMapTreeMap
Basic
HashMap does not keep track of the order of insertions.
TreeMap preserves insertion order.
Interface Implements
Map, Cloneable, and Serializable interfaces are all ones that are implemented by HashMap.
TreeMap is capable of being Cloned and Serialized, in addition to implementing the NavigableMap interface.
Data Structure
A Hash Table serves as the foundation for HashMap's underlying data structure.
The Red-Black Tree is the foundational data structure that TreeMap is built upon.
Null Keys and Values
The Null key can be used once in HashMap, and the Null value can be used any number of times.
TreeMap does not let the use of a null key, but it does permit the use of a null value any number of times.
Extends and implements
The HashMap class is an extension of the AbstractMap class and an implementation of the Map interface.
The TreeMap class extends the AbstractMap base class and implements the SortedMap and NavigableMap interfaces respectively.
Performance
HashMap processes operations more quickly.
When compared to HashMap, the operation speed of TreeMap is lower.
Order of elements
HashMap does not keep track of order.
The elements are arranged in their natural order (ascending).
Homogeneous/ Heterogeneous
HashMap supports heterogeneous elements because it does not perform key sorting.
Because of sorting, TreeMap allows homogeneous values as keys.
Uses
When we do not want key-value pairs to be in sorted order, the HashMap data structure should be utilised.
When we need the key-value pair to be in sorted (ascending) order, we should utilise the TreeMap.

## Conclusion

You should use a TreeMap only in situations where a sorted list of key-value pairs is required. There is a performance cost involved in sorting. A HashMap operates more quickly because it is not synchronised.