TreeMap in Java

TreeMap in Java provides an efficient way of storing key/value pairs in sorted order and allows rapid retrieval of the elements in map. The TreeMap class extends AbstractMap and implements the NavigableMap interface.
It creates maps stored in a tree structure.

TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time.

TreeMap is a generic class which has below declaration:

class TreeMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

Constructors provided by TreeMap:

TreeMap( )
TreeMap(Comparator<? super K> comparator)
TreeMap(Map<? extends K, ? extends V> map)
TreeMap(SortedMap<K, ? extends V> sortedMap)

The first form of constructor creates an empty tree map that will be sorted by using the natural order of its keys. The second form creates an empty tree-based map that will be sorted by using the Comparator comparator. The third form initializes a tree map with the entries from map, which will be sorted by using the natural order of the
keys. The fourth form initializes a tree map with the entries from sortedMap, which will be sorted in the same order as sortedMap.

TreeMap in Java is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.

Example:

Output:

You can also learn about

Related posts

Leave a Comment