The TreeMap data structure stores key-value pairs and allows you to perform CRUD operations on this data.

How to Create a TreeMap in Java

The TreeMap class has four constructors that you can use to create a new TreeMap object. The default constructor is the most popular of the four. This constructor takes no arguments and generates an empty tree map.

The code above generates an empty tree map called customers.

Populating the TreeMap Data Structure

The put() method adds an item to a TreeMap object. It takes two arguments—a key and its value. You can add items to the tree map in any random order and the data structure will store them in ascending order, according to their keys.

The code above adds five customers, in random order, to the customers tree map.

Viewing Items in a TreeMap

The TreeMap class stores its data in an object. So, to see all the items in a tree map you can simply print the tree map object to the console:

The code above prints the following output to the console:

Note that the object above displays the items in ascending order. You can also view each item and its corresponding key using a Java for loop.

The code above prints the following output to the console:

Updating Items in a TreeMap

The TreeMap class allows you to update an existing item using the replace() method. There are two replace methods. The first method takes an existing key and the new value you want to map the existing key to.

The code above prints the following object in the console:

As you can see Kim Brown is now Kim Smith. The second replace() method takes an existing key, the key’s current value, and the new value you want to map to the key.

The code above prints the following object in the console:

In the object above Michelle Noah replaces Jim Riley.

Deleting Items From the TreeMap

If you want to remove a single item from the tree map, the remove() method is your only option. It takes the key associated with the item you want to remove and returns the deleted value.

Running the code above prints the following object to the console:

This Java Class also has a clear() method that allows you to delete all the items in the tree map.

The TreeMap vs. the HashMap Java Class

TreeMap and HashMap are two of the more popular Java map classes. They both extend the AbstractMap class. This relationship gives the TreeMap and HashMap classes access to a lot of the same functions.

However, there are some noteworthy differences between these two map classes. The TreeMap uses a Red-Black tree implementation of the Map interface, while the HashMap uses a hash table. HashMap allows you to store a single null key, while TreeMap does not. Finally, a HashMap is faster than a TreeMap. The former’s algorithmic speed is O(1) while the latter’s is O(log(n)).