Map is an object that maps keys to values. A map cannot contain duplicate keys.
TreeMap class is a red-black tree based NavigableMap implementation. It stores its elements in a red-black tree, which is a self-balancing binary search tree.
TreeMap is substantially slower than HashMap, but the elements are ordered based on their value.
TreeMap differs from HashMap in that it orders its elements in ascending order of their keys. That is, regardless of the insertion order of the elements, all elements are ordered in ascending order of their keys (their natural ordering to be precise).
TreeMap class permits
null values but not the
Java provides the TreeMap class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
The following example illustrates the TreeMap class.
As you can see from the above output, TreeMap ordered the elements in ascending order of their keys.
The above program showed the use of some of the common methods of the TreeMap class. For a complete list of all the available methods, refer the official docs.
Now since you know how to use the TreeMap class, check out other implementations of the Map interface: