TreeMap Tutorial Java

TreeMap Tutorial Java


TreeMap is derived from SortedMap interface and attains the property of printing the elements in ascending order. With Comparator, the order can be changed. The Comparator should be supplied at the time of TreeMap object creation itself.

Methods of TreeMap are not synchronized and thereby not thread-safe. Using in multithreaded environment is not advisable. A synchronized version can be obtained as follows.

TreeMap tm1 = new TreeMap();
Map m1 = Collections.synchronizedMap(tm1);

The Map m1 methods are synchronized and suitable for the usage where multiple threads access is required. But, still tm1 is not synchronized.

We can obtain unmodifiable (read-only) version also as follows.

TreeMap tm2 = new TreeMap();
Map m2 = Collections.unmodifiableMap(tm1);

Now the Map m2 is read-only and thereby any delete or addition operations do not work and if performed, the JVM throws UnsupportedOperationException.

Following is the class signature

public class TreeMap extends AbstractMap implements SortedMap, Cloneable, Serializable

TreeMap Tutorial on Constructors
  1. TreeMap(): Creates TreeMap object without any elements. Elements (key/value pairs) can be put afterwards.
  2. TreeMap(Comparator comp): Creates TreeMap object without any elements. Elements (key/value pairs) can be put afterwards. The Comparator object comp changes the ordering of elements (the natural order is ascending).
  3. TreeMap(Map map1): Creates a TreeMap object containing the elements of Map map1. Like this, we can add the elements of one map to another.
  4. TreeMap(SortedMap smp1): Creates a TreeMap object containing the elements of SortedMap smp1. It can be done with putAll() method also.
TreeMap Tutorial on Methods

TreeSet can make use of the methods of Map and SortedMap and adds its own as follows.

  • Object clone(): A TreeMap object can be cloned.

Two programs are given on TreeMap with the following operations.

  1. TreeMap General: The general operations like object creation, addition and deletion of key/value pairs, knowing the existence of a key or value or elements and size etc. are performed.
  2. TreeMap Special: The special operations like sorting the elements on key basis and value basis, adding elements (key/value pairs) of one tree map to another at object creation and later, extracting a part of a tree map into another etc. are shown.

One thought on “TreeMap Tutorial Java

Leave a Reply

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