Monday, December 12, 2011

TreeMap in Java is a SortedMap and it maintains Sorting order when you insert 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 by 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 specific constructor for these conditions. We will see these in section of creating instance of TreeMap in Java. We will also see how to put element, get element, iterate over TreeMap, clearing and reusing TreeMap in this Java TreeMap tutorial. This article is in continuation of my collection series e.g. HashMap vs HashSet , SynchronziedHashMap vs ConcurrentHashMap and Iterator vs Enumeration in Java

Java TreeMap Tutorial and Example

Creating TreeMap in Java using natural ordering of keys

Here are few ways to create TreeMap in Java:

TreeMap in Java using 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 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 implements Map interface with difference in that key in TreeMap are sorted.

Add object into TreeMap in Java

Now inserting or adding object into TreeMap is very simple, you need to use same put(key, value) method which is available form 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 new object is not convertible into type of Object TreeMap is holding.

assetClassMap.put("Foriegn Exchange", "FX is converting currency from one to other e.g. USD to YEN");

Retrieve object from TreeMap

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

assetClassMap.get("Equity");

assetClassMap.get("Derivative");

How to clear TreeMap in Java

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

assetClassMap.clear();

How to get Comparator from TreeMap

If you have created TreeMap in Java by providing an external comparator than 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();

Checking a value exists in Java TreeMap

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

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

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 specified key or return false if TreeMap doesn't contains that key.

assetClassMap.containsKey("Derivatives");

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 method descendingMap() which returns a NaviagableMap. descendingMap is backed by original TreeMap and nay 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.

How to get first entry from TreeMap in Java

Since TreeMap is a SortedMap we can get both first and last entry from TreeMap. TreeMap in

Java provides convenient method to get firstKey and lastKey from TreeMap. Below is example of TreeMap and getting first key and first entry. FirstKeywill throw NoSuchElementException exception if TreeMap is empty while firstEntry will return null.

assetClassMap.firstEntry();

assetClassMap.firstKey();

How to get last entry from Java TreeMap

Similar to above example of getting first entry and first key you can also get last entry and lastkey from treeMap in Java as shown in below Exmaple 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 earlier example of getting first entry from treeMap in Java. You can also get last entry from Java TreeMap.

Creating subMap from TreeMap in Java

From JDK 1.6 onwards we have a subMap() method in TreeMap which returns portion of Map while key range is specified by fromKey to toKey. The returned Map is backed by 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 and IllegalArgumentException when you insert a key outside of its range.

Inline with 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 equalto 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 Above example of headMap and tailMap, headTreeMap will contain zero elements because "Derivative" is lowest key and there is no key which is less than that and tailTreeMap will contains four entries because every other entries e.g. Equities, Fixed Income and foreign exchange is greater than Derivatives.

Checking whether TreeMap is empty

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

boolean isEmpty = assetClassMap.isEmpty();

How to find Size of TreeMap in Java

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

int size = assetClassMap.size();

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 iterator's remove() method.

assetClassMap.remove("Equity");

That's all on TreeMap in Java. Please raise any question 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.

5 comments
:

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.

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.