java tutorial - Java TreeMap class - java programming - learn java - java basics - java for beginners
Learn Java - Java tutorial - Java treemap - Java examples - Java programs
Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
- A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
- It contains only unique elements.
- It cannot have null key but can have multiple null values.
- It is same as HashMap instead maintains ascending order.
Learn java - java tutorial - treemap - java examples - java programs
TreeMap class declaration
Let's see the declaration for java.util.TreeMap class.
TreeMap class Parameters
Let's see the Parameters for java.util.TreeMap class.
- K: It is the type of keys maintained by this map.
- V: It is the type of mapped values
Constructors of Java TreeMap class
Constructor | Description |
---|---|
TreeMap() | It is used to construct an empty tree map that will be sorted using the natural order of its key. |
TreeMap(Comparator comp) | It is used to construct an empty tree-based map that will be sorted using the comparator comp. |
TreeMap(Map m) | It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys. |
TreeMap(SortedMap sm) | It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm. |
Methods of Java TreeMap class
Method | Description |
---|---|
boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key. |
boolean containsValue(Object value) | It is used to return true if this map maps one or more keys to the specified value. |
Object firstKey() | It is used to return the first (lowest) key currently in this sorted map. |
Object get(Object key) | It is used to return the value to which this map maps the specified key. |
Object lastKey() | It is used to return the last (highest) key currently in this sorted map. |
Object remove(Object key) | It is used to remove the mapping for this key from this TreeMap if present. |
void putAll(Map map) | It is used to copy all of the mappings from the specified map to this map. |
Set entrySet() | It is used to return a set view of the mappings contained in this map. |
int size() | It is used to return the number of key-value mappings in this map. |
Collection values() | It is used to return a collection view of the values contained in this map. |
Java TreeMap Example:
Output
Java TreeMap Example: remove()
Output:
What is difference between HashMap and TreeMap?
1) HashMap can contain one null key. | TreeMap can not contain any null key. |
2) HashMap maintains no order. | TreeMap maintains ascending order. |