Tuesday, August 17, 2021

Java TreeMap Tutorial: 15 Example of TreeMap in Java

TreeMap in Java is a SortedMap and it maintains Sorting order when you insert an object on it. You can specify Sorting order while Creating TreeMap by providing an explicit Comparator to TreeMap. Basically, you can create TreeMap in Java in different ways, a TreeMap with natural sorting order, and TreeMap with custom Sorting Order by providing Comparator, Copying Sorting order from other SortedMap, etc. TreeMap has a specific constructor for these conditions. We will see these in the section on creating instances of TreeMap in Java. 


We will also see how to put elements, get elements, iterate over TreeMap, clearing and reusing TreeMap in this Java TreeMap tutorial

This article is in continuation of my collection series like HashMap vs HashSet, SynchronziedHashMap vs ConcurrentHashMap, and Iterator vs Enumeration in Java


Java TreeMap Example and Tutorial

Without wasting any more of your time, here are 10 examples of TreeMap in Java

1. Creating TreeMap in Java using the natural ordering of keys

Here are few ways to create TreeMap in Java:

TreeMap in Java using the natural ordering of keys

TreeMap naturalOrderMap = new TreeMap();

TreeMap with custom sorting order



TreeMap customSortingMap = new TreeMap(Comparator comparator)

Objects stored in this TreeMap will be ordered according to the given Comparator.

TreeMap from existing SortedMap

TreeMap sameOrderMap = new TreeMap(SortedMap sm)

This TreeMap will have the same mappings and order as specified by provided SortedMap. TreeMap is similar to HashMap in Java as both implement Map interface with differences in that keys in TreeMap is sorted.

2. Add object into TreeMap in Java

TreeMap in Java Example tutorialNow inserting or adding objects into TreeMap is very simple, you need to use the same put(key, value) method which is available from Map. Below is an example of putting objects into TreeMap. What is important here is that TreeMap sorts object as soon as you insert them and throws ClassCastException if a new object is not convertible into the type of Object TreeMap is holding.

assetClassMap.put("Fixed Income", "Fixed income is related to bonds, Fixed Deposit, Swaps etc");
assetClassMap.put("Equity", "Equity is related to Stock trading in Cash also called Cash Equity");
assetClassMap.put("Derivative", "Derivative is mostly futures, options trading ");
assetClassMap.put("Foriegn Exchange", "FX is converting currency from one to other e.g. USD to YEN");


3. Retrieve object from TreeMap

Simple just use get(key) method and provide key and it will return value from TreeMap.

assetClassMap.get("Equity");
assetClassMap.get("Derivative");


4. How to clear TreeMap in Java

You can reuse the same TreeMap for different purposes by clearing it. clear()  will remove all entries from TreeMap and make it empty. Beware of clearing Map in a multi-threading environment where it could be possible that before you clear some other thread read old values.

assetClassMap.clear();



5. How to get Comparator from TreeMap

If you have created TreeMap in Java by providing an external comparator then you can get that Comparator by comparator() method of TreeMap. But if you are sorting values by natural order this method will return null.

Comparator comparator = assetClassMap.comparator();



6. Checking a value exists in Java TreeMap

Sometimes we want to see whether a particular value exists in TreeMap or not, this is quite easy by using the utility method containsValue(Object value) of the TreeMap class in Java. This method returns true if TreeMap contains a specified value otherwise return false.


assetClassMap.containsValue("does it contain equities trading info");



7. How to check a key exists in TreeMap

Just like checking for values in treeMap in Java, you can also search for keys by using method containsKey this method will return true if you contain a specified key or return false if TreeMap doesn't contain that key.

assetClassMap.containsKey("Derivatives");



8. How to get a reverse order view of Mapping from TreeMap

From JDK 1.6 onwards you can get a reverse order view of mapping contains in TreeMap in Java by using the method descendingMap() which returns a NaviagableMap. 

The descendingMap() is backed by the original TreeMap and any change in either of Map will reflect at both places. If any of TreeMap modified during an iteration except through Java iterator's remove method result of the iteration is undefined.'


NavigableMap reverseTreeMap = assetClassMap.descendingMap();

You can also get reverse order treeMap by using Collections.reverseOrder(Comparator) which is available from Java5 onwards. 

Similarly, you can also get descending keySet by calling method descendingKeySet which returns a NavigableSet with reverse orders of key. Read more about Comparator and comparable in Java here.


9. How to get the first entry from TreeMap in Java

Since TreeMap is a SortedMap we can get both the first and last entry from TreeMap. TreeMap in Java provides a convenient method to get firstKey() and lastKey() methods from TreeMap. 

Below is an example of TreeMap and getting the first key and first entry. FirstKeywill throw NoSuchElementException exception if TreeMap is empty while firstEntry() will return null.

assetClassMap.firstEntry();
assetClassMap.firstKey();



10. How to get the last entry from Java TreeMap

Similar to the above example of getting the first entry and first key you can also get the last entry and lastkey from treeMap in Java as shown in the below Example of TreeMap.

Similar to firstKey and firstEntry in TreeMap lastkey will throw NoSuchElementException if TreeMap is empty while lastEntry will just return null.

assetClassMap.lastEntry();
assetClassMap.lastKey();

Similar to the earlier example of getting the first entry from treeMap in Java. You can also get the last entry from Java TreeMap. You can use these methods to get the highest and lowest entries from the TreeMap in Java because TreeMap stores entires in a sorted order specified by the Comparable or Comparator provided. 

I used these methods on TreeSet, which is backed by TreeMap to retrieve the highest and lowest elements to process.  


11. Creating subMap from TreeMap in Java

From JDK 1.6 onwards we have a subMap() method in TreeMap which returns a portion of Map while the key range is specified by fromKey to toKey. The returned Map is backed by the original TreeMap and any change made in subMap will reflect back in TreeMap and vice-versa.

Returned subMap also supports all optional Map operations that this Map supports. SubMap will throw an IllegalArgumentException when you insert a key outside of its range.

SortedMap subMap = assetClassMap.subMap("Derivative", "Foriegn Exchange");



12. Creating headMap and tailMap from TreeMap in Java

In line with the above example of getting SubMap from TreeMap you can also get headMap and tailMap from treeMap on Java6 onwards.headMap(K toKey,boolean inclusive) is used to get headMap which is a part of original Map whose keys are less than or equal to toKey. tailMap is opposite to headMap where keys are greater than(or equal to, if inclusive is true)fromKey

SortedMap headTreeMap = assetClassMap.headMap("Derivative");
SortedMap tailTreeMap = assetClassMap.tailMap("Derivative");

In the Above example of headMap and tailMap, headTreeMap will contain zero elements because "Derivative" is the lowest key and there is no key that is less than that and tailTreeMap will contain four entries because every other entry e.g. Equities, Fixed Income, and foreign exchange are greater than Derivatives.


13. Checking whether TreeMap is empty

There is a convenient isEmpty()method from AbstactMap which is used to check whether TreeMap in java is empty or not, its return is true if TreeMap doesn't contain any entry.

boolean isEmpty = assetClassMap.isEmpty();


14. How to find the Size of TreeMap in Java

TreeMap in java provides a size() method which can be used to get a total number of elements in Java.

int size = assetClassMap.size();


15. Removing objects from TreeMap in Java

remove(Object key) method is used to remove any mapping from Java TreeMap. Don’t use this while iterating, instead use the iterator's remove() method.

assetClassMap.remove("Equity");


That's all on TreeMap in Java. Please raise any questions or doubts you have on using TreeMap in Java or any Example of Java TreeMap and we will see how we can solve that. In Summary TreeMap in Java is an important Collection class and pretty useful for Sorting.


Some more Java Tutorials you may like

7 comments :

KidCrippler said...

Great tutorial, would be very useful for novice programmers using TreeMap for the first time.

One question though - why did you call it a TreeMap tutorial and not a SortedMap tutorial?
Everything in this article can also be said about any other class that implements the SortedMap interface, and nothing about the "Tree" part of the TreeMap was mentioned.

Again, great tutorial :-)

extremejava said...

I would add that TreeMap implements SortedMap interface and also extends AbstractMap class.
7 Points on Exceptions in Effective Java

Javin @ spring interview questions answers said...

Indeed TreeMap extends AbstractMap and @KidCrippler thanks for your comment. Tree part of TreeMap is that it is based on Red Black Tree based NavigableMap and yes it applies to all SortedMap :)

Johnny Lim said...

Rather Simple examples of TreeMap than the complex one like How to sort TreeMap on different order than natural order of element or How TreeMap works internally. to add I would say that whenever a new element is inserted in TreeMap it sort the object in order of its key. If you are intention is just to sort element than consider using TreeSet instead of TreeMap.

java67 said...

See here for Difference between TreeMap and TreeSet in Java.

Unknown said...

Hi Javin,
I have few questions on treemap,
1) is treemap hash based collection?
2) is our custom object used as key in treemap should implement equals() & HashCode() methods?
3) How treemap maintains Uniqueness of key's?

I am not able to get correction answer for the above question in google could you please help me with detailed explanation for my questions.

Thanks,
Chiranjeevi

javin paul said...

@Chiranjeevi, Please find my answers below
1) No, TreeMap is not a hash based collection instead it's a tree based collection. It internally uses Red Black Tree to hold elements. You can check get() method of TreeMap, it doesn't call hashCode() method to find the bucket location.

2) Since TreeMap is not hash based, hashCode is not mandatory, but your custom object must implement either Comparable or Comparator so that it can be arranged in sorted order in a Red Black tree. Since compare() or compareTo() should be consistent with equals(), you end up overriding equals() and hashCode() as well.

3) TreeMap uses compareTo() or compare() to compare keys. if compareTo() return 0 which it should for equal object then existing value is updated.

your questions were quite good and helped to explore TreeMap in details, so feel free to post if you have any more questions.

Post a Comment