TreeMap in Java

Posted on Updated on

The TreeMap class implements the Map interface which store key-value pairs in tree data structure. It provides an efficient means of storing key/values pairs in sorted order.

Followings are the features of TreeMap.

  1. It contains only unique elements.
  2. It can’t have null key but can have multiple null values.
  3. It is not synchronized i.e not safe for multi-threaded application.
  4. It is same as HashMap instead maintains ascending order.

TreeMap provides following constructors.

Constructor Description
TreeMap() Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the interface.
TreeMap(Comparator comparator) Constructs a new empty treemap, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator.
TreeMap(Map map) Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys. All keys inserted into the new map must implement the interface.
TreeMap(SortedMap map) Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method runs in linear time.

Example of TreeMap

Output

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.