TreeMap in Java, just like the HashMap, is part of the java collection framework. It is a red-black tree-based implementation of the Map interface, NavigableMap, and AbstractMap classes. It stores data in the form of Key and Value pairs where the key is a unique identifier used to associate each value on the Map. It means that every key is mapped to exactly one value and that we can use it to retrieve its corresponding value from the map.
Now that we have a general idea about TreeMap, Let’s dive into its more advanced features for a better understanding.
- What is a TreeMap?
- Initializing a TreeMap
- Features of TreeMap
- Why is TreeMap not Synchronized in Nature?
- Internal Structure of TreeMap.
- Basic Operations of TreeMap.
- Some more Methods of TreeMap in Java
- Constructors in TreeMap
- Sorting in TreeMap
- Internal Working of TreeMap
- Red-Black Tree Algorithm
- Step-by-Step Procedure for Working on TreeMap
- Frequently Asked Question
What is a TreeMap?
As mentioned above, TreeMap is nothing more than a Data Structure that stores data in the form of the key and value pair, where the key should be a unique identifier that allows us to perform multiple operations like add, delete, replace, etc on the data stored in the TreeMap.
Unlike HashMap which only takes a constant time, it takes a logarithmic time to perform the above-mentioned operations. This makes one wonder why it was introduced in the first place. The answer is simple…to save the memory used to store data. It only uses the amount of memory needed to hold/ store the items, unlike a HashMap which uses a contiguous region of memory.
The best thing about TreeMap is that here storing of data is done based on the natural ordering of keys — if keys are initialized as integers then they will be stored in ascending order of the keys, and if the keys are initiated as String or characters, then the data will be stored in the alphabetic order.
But in the case of TreeMap custom sorting is also possible. For that, we have to use a specific type of constructor to perform this custom sort which we will see later in the blog.
The ordering maintained by a TreeMap (just like any other sorted map) must be compatible with the equal sign if it correctly wants to implement the Map interface irrespective of whether a constructor is provided or not. This is because all the operations performed on the map Interface use the equal operator, while all the operations performed on the Sorted map use its compareTo or compare method.
Initializing a TreeMap
Creating a TreeMap is the same as creating a HashMap in Java. Just like in HashMap, first, we have to import the TreeMap class from the util package and then write the following line to create a new TreeMap in Java and use all its methods and constructor.
TreeMap<Key, Value> numbers = new TreeMap<>()
key — is the unique identifier used to associate each element in the map
value — elements associated by keys in a map.