Java TreeMap Tutorial with Examples

Java TreeMap tutorial with examples will help you understand how to use the Java TreeMap class in an easy way. TreeMap in Java is a tree based implementation of the Map interface. The TreeMap class implements the NavigableMap interface. Unlike the HashMap class, the keys of the TreeMap are sorted according to the natural ordering or by the custom comparator.

Java TreeMap hierarchy

If you do not want the keys to be sorted by their natural ordering but by custom order, you can do so by providing the custom Comparator at the time of TreeMap creation using the below given constructor.

The TreeMap in Java provides log(n) time cost for get, put, remove and containsKey operations.

The TreeMap implementation is not synchronized. If multiple threads are trying to modify the TreeMap object simultaneously, then the access must be synchronized explicitly. You can either synchronize the TreeMap object or you can get the synchronized SortedMap object from the existing TreeMap using the synchronizedSortedMap method of the Collections class as given below.

The Iterator object obtained by the iterator method of the TreeMap is fail-fast. That means if the TreeMap object is structurally modified after obtaining the iterator (except by using iterator’s own remove method), calling any methods of the iterator object will throw ConcurrentModificationException.

How to create TreeMap objects?

The TreeMap class in Java provides several constructors to create the objects. The default constructor of the TreeMap class creates a new empty TreeMap object. The key-value pairs stored in this TreeMap object are stored by the natural ordering of its keys.

Output

As you can see from the output, the treemap entries are sorted by keys using the natural ordering.

If you want to specify the custom order, use the overloaded constructor having the Comparator argument.

The objects in this TreeMap will be sorted by the keys in the order defined by the provided custom comparator.

Output

As you can see from the output, the mappings are now sorted in descending order by the custom comparator we provided in the TreeMap constructor.

The TreeMap class in Java also provides an overloaded constructor that accepts the Map argument. Using this constructor you can convert HashMap to TreeMap.

This constructor creates a new TreeMap having the same key value pairs as the given map object ordered by the natural ordering of the keys. Important: All the keys inserted in the TreeMap must implement the Comparable interface.

Output

How to add objects to TreeMap using the put, putAll, and putIfAbsent methods?

The TreeMap put method adds given key and value to the treemap object. If the TreeMap already contains the key, the value associated with the key will be replaced by the new value. In this case, the previous value will be returned. It returns null if there was no value associated with the key previously.

Output

Similarly, the putAll method of the TreeMap class copies all the mappings contained in the given map object to this treemap object.

Output

As you can see from the output, the key-value pairs copied from the HashMap will be automatically inserted into the TreeMap object in sorted order.

The putIfAbsent method of the TreeMap class adds a key-value mapping to the TreeMap object if the key is not currently associated with any value and returns null. If the specified key already exists in the TreeMap, the putIfAbsent method does nothing and returns the value associated with the specified key.

Output

Difference between put and putIfAbsent methods: If the specified key is already mapped to some value in the TreeMap, the put method replaces the value currently associated with the specified key with the new value, while the putIfAbsent method does not do anything.

How to get objects from TreeMap?

1. How to get the value mapped to a key from the TreeMap using get method?

The get method of the TreeMap class returns a value associated with the given key. If the key does not exist in the TreeMap, it returns null.

Output

2. How to get a default value for a key if the key does not exist in the TreeMap?

The getOrDefault method returns the value associated with the specified key if the key is mapped to some value in the TreeMap. If the mapping does not exist for the key, it returns the specified default value instead of null.

Output

3. How to get the first key, first value, or first entry from the TreeMap?

The TreeMap class in Java provides the firstEntry and firstKey methods to get the first entry and first key stored in the treemap object respectively.

Output

4. How to get the last key, last value, or last entry from the TreeMap?

The lastEntry and lastKey methods of the TreeMap class return the last entry and last key stored in the treemap object respectively.

Output

5. How to get the key greater than the specified key from the TreeMap?

Using the higherKey and higherEntry methods:

The higherKey method returns a key greater than the specified key from the TreeMap. Similarly, the higherEntry method returns an entry from the TreeMap having a key greater than the specified key.

Output

Using the ceilingKey and ceilingEntry methods:

The ceilingKey method returns the smallest key from the TreeMap that is greater than or equal to the specified key. Similarly, the ceilingEntry method returns an entry having the smallest key that is greater than or equal to the specified key.

Both of these methods return null if there is no such key in the TreeMap.

Output

What is the difference between the higherKey and ceilingKey methods? Well, the higherKey method returns the key which is strictly greater than the specified key, while the ceilingKey method returns the smallest key which is equal to or greater than the specified key.

6. How to get the key less than the specified key from the TreeMap?

Using the lowerKey and lowerEntry methods:

The lowerKey method returns a key lower than the specified key from the TreeMap. If there is no such key, it returns null. Similarly, the lowerEntry method returns an entry having a key which is lower than the specified key. If there is no such lower key, it returns null.

Output

Using the floorKey and floorEntry methods:

The floorKey method returns the largest key which is equal to or less than the specified key. It returns null if there is no such key. Similarly, the floorEntry method returns an entry having the largest key which is less than or equal to the specified key. This method also returns a null if there is no such key.

Output

Difference between lowerKey and floorKey methods: The lowerKey method returns a key which is strictly lower than the specified key while the floorKey method returns the largest key which is equal to or lower than the specified key.

How to get the size of the TreeMap using the size method?

The size method returns the number of entries stored in the TreeMap object. It returns 0 if the TreeMap object is empty.

Output

How to get all the keys from TreeMap using the keySet method?

The keySet method of the TreeMap class returns a Set view containing all the keys stored in the TreeMap object.

Output

The Set returned by the keySet method is backed by the original treemap object. That means, if any of the keys is removed from the Set, it will be removed from the TreeMap too.

Output

How to get all the values from TreeMap using the values method?

The values method returns a Collection view containing all the values stored in the TreeMap object. The Collection returned by this method is backed by the original map object. So any changes you make to a TreeMap object will be reflected back to the Collection, and vice versa.

Output

How to get all the key value pairs or entries from the TreeMap using the entrySet method?

The entrySet method of the TreeMap class returns a Set view containing all the key-value mapping of the TreeMap object. Just like the entrySet and values methods, the Set returned by this method is also backed by the original treemap object. So any changes you make to the Set will also be reflected back the TreeMap object, and vice versa.

Output

How to replace a value in TreeMap using the replace method?

The replace method replaces a value mapped to a given key with the given new value, only if the given key is mapped to some value. It returns the old value which was mapped to the specified key previously, or a null if the key does not exist in the TreeMap object.

Output

If you call the put method with the key which already exists, it will also replace the value associated with the key with the given new value.

Output

Then what is the difference between replacing a value using the put method and replacing a value using the replace method? Well, the difference is, if the key does not exist in the TreeMap, the put method creates a new key-value mapping while the replace method does nothing and returns null.

If you want to replace a value for a given key, only if the key is mapped to a specific value, use an overloaded replace method.

The value will be replaced for a given key, if and only if the key is currently mapped to the given oldValue. This method returns true if the key-value mapping was found and oldValue is replaced with the newValue, false otherwise.

Output

How to check if the key is present in the TreeMap using the containsKey method?

The containsKey method of the TreeMap class returns true if the key exists in the TreeMap, false otherwise.

This method throws ClassCastException if the given key cannot be compared with the keys contained in the TreeMap object.

Example:

Output

How to check if the value is present in the TreeMap using containsValue method?

The containsValue method of the TreeMap class returns true if the treemap object has the specified value mapped to one or more keys. It returns false otherwise.

Output

How to delete a key value pair from the TreeMap?

1. Remove a key value pair using the remove method

The remove method removes a key value mapping from the treemap object for the specified key. If the key is found in the map, it deletes the mapping and returns the value which was mapped to the key. If mapping is not found, it returns null. Although, do not rely on the null return value, as the specified key might as well be mapped to the null value.

Output

The above given remove method removes a key-value mapping if the specified key is mapped to any value in the TreeMap. If you want to remove the mapping only if the specified key is mapped to a specified value, then use the below given overloaded remove method.

This method removes a mapping if and only if the specified key is mapped to the specified value.

Output

2. Remove first key value mapping using the pollFirstEntry method

The pollFirstEntry method removes and returns the first mapping of the TreeMap. It returns null if the TreeMap is empty.

Output

3. Remove last key value mapping using the pollLastEntry method

The pollLastEntry method removes and returns the last mapping of the TreeMap. It returns null if the TreeMap is empty.

Output

How to check if the TreeMap is empty using the isEmpty method?

The isEmpty method returns true if the TreeMap contains no key value pairs. It returns false otherwise.

Output

You can also compare the return value of the size method with 0 to check if the TreeMap is empty instead of using the isEmpty method. However, the isEmpty method is a recommended way as it is more readable.

How to empty the TreeMap using the clear method?

The clear method of the TreeMap class removes all the mappings from the TreeMap i.e. deletes all the key-value pairs or empty the TreeMap.

Output

How to clone the TreeMap using the clone method?

The clone method of the TreeMap class creates a shallow copy of this treemap object. The clone method does not deep clone the TreeMap, which means the keys and values are not cloned.

Output

As you can see from the output, the original and cloned TreeMap objects contain the same key value pairs. However, since its a shallow copy, only the references to the keys and values are copied, not the actual objects. They still refer to the same objects. Refer to the below given example to understand it.

Output

How to get submap from the TreeMap?

1. How to get the submap of TreeMap using the subMap method?

The subMap method returns a portion of the TreeMap whose keys range from the startKey to endKey. The startKey is inclusive while the endKey is exclusive.

Example:

Output

The submap returned by this method is backed by the original map, so any changes you make to the submap will also be reflected back to the original TreeMap object.

Output

Plus, if you try to insert any mapping having a key that is out of the range of the submap, it throws IllegalArgumentException: key out of range exception.

Output

In the above given submap method, the startKey is inclusive while the endKey is exclusive. If you want to change the startKey or endKey being inclusive or exclusive, you can use an overloaded subMap method.

The startKeyInclusive and endKeyInclusive parameters control the inclusiveness or exclusiveness of the start and end keys. If the startKeyInclusive parameter is true, the startKey becomes inclusive. If it is false, the startKey becomes exclusive. The same applies to the endKey and endKeyInclusive parameters.

2. Get the submap having keys greater than the specified key using the tailMap method

The tailMap method returns a submap or portion of the TreeMap whose keys are greater than or equal to the specified key. The submap returned from this method is backed by the original TreeMap, so any changes you make in the submap will be reflected back to the TreeMap, and vice versa.

Example:

Output

Similar to the map obtained using the submap method, If you try to put a key which is out of the range of the submap, it throws IllegalArgumentException: key out of range exception.

There is an overloaded tailMap method that has an additional parameter that controls the inclusiveness of the fromKey.

If the fromKeyInclusive parameter is true, the submap will have the keys greater than or equal to the fromKey. If it is false, the submap will have keys greater than the specified fromKey.

3. Get the submap having keys less than the specified key using the headMap method

Similar to the tailMap method, the headMap method returns a submap having keys strictly less than the specified key. The submap returned from this method is backed by the original TreeMap, so any changes you make in the submap will be reflected back to the TreeMap, and vice versa.

Example:

Output

Use an overloaded headMap method to control the inclusiveness of the toKey parameter.

If the toKeyInclusive parameter is true, the toKey is included in the submap returned by this method. If it is false, only keys less than the specified keys will be included in the submap. Both of these methods throw IllegalArgumentException: key out of range exception if you try to put a key value pair having the key out of the range of the submap.

How to iterate TreeMap in Java?

The TreeMap tutorial is incomplete without learning how to iterate the TreeMap. There are several ways to iterate through the TreeMap object.

1. How to iterate through keys of TreeMap?

The keySet method returns the Set view of the keys stored in the TreeMap object. We can iterate the key Set using the enhanced for loop.

Output

2. How to iterate through the values of TreeMap?

The values method returns a Collection view of all the values stored in the TreeMap object. We can iterate through the values using the enhanced for loop just like iterating the keys.

Output

3. How to iterate through key-value pairs of TreeMap?

The entrySet method returns the Set view of the entries i.e. key-value pairs stored in the TreeMap object. We can iterate through the TreeMap entries using enhanced for loop, while loop, or for loop.

Iterate TreeMap using enhanced for loop:

Output

Iterate TreeMap using while loop:

Output

Iterate TreeMap using for loop:

Output

The below given additional Java TreeMap examples discuss the concepts in more detail.

Java TreeMap Examples

References:
Java TreeMap class Javadoc

Please let me know if you liked the Java TreeMap tutorial with examples in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *