TreeMap Example Java

TreeMap Example Java

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.

This is the first program of the above two where general operations are done. Before going into this program, it is advised to go through TreeMap Tutorial and also to know first about the Map, SortedMap interfaces and Map methods as TreeMap is derived from them and uses as it is all the methods of Map interface.

TreeMap tm1 = new TreeMap();
System.out.println(“tm1 isEmpty() before adding elements: ” + tm1.isEmpty());
tm1.put(“one”, 1);

A non-generic TreeMap object tm1 is created and checked for its emptiness. isEmpty() method, inherited from Map interface, returns true if no elements (key/value pair) exists. The above statement returns true as tm1 is empty without elements added yet. With put() method, inherited from Map, a few key/value pairs are added.

System.out.println(“\napple key exists: ” + tm1.containsKey(“apple”));
System.out.println(“red value exists: ” + tm1.containsValue(“red”));

The existence of a key or a value can be checked with containsKey() and containsValue() methods, inherited from Map interface. These methods return true if the key and value exists with TreeMap tm1.

System.out.println(“\nValue of three: ” + tm1.get(“three”));

With get() method, inherited from Map, the value of a key can be retrieved, by supplying the key.


remove() and clear() methods, inherited from Map, are used to delete elements from the TreeMap, but with a difference. remove() deletes only one element where as clear() deletes all at a time.

In this program, all the simple operation of day-to-day are discussed. In the next program TreeMap Special, the special operations like extracting a part of TreeMap elements (using subMap(), headMap() and tailMap()), iterating, sorting etc. are performed.

Leave a Reply

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