TreeMap

Java TreeMap is a tree based implementation of the Map interface. The TreeMap class implements NavigableMap interface. Unlike the HashMap class, the TreeMap class is sorted according to the natural ordering of the keys.

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 below constructor.

public TreeMap(Comparator comparator)

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

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

SortedMap sortedMap = Collections.synchronizedSortedMap(existingTreeMapObject);

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.

Below given are some of the Java TreeMap examples which shows how to use TreeMap in Java.

Java TreeMap Examples

Join 1000+ fellow learners! Enter your email address below: