TreeMap example in Java

TreeMap is a part of the java.util package and implements the Map interface. TreeMap stores the Key-Value pairs in a sorted order of the Keys.

TreeMap is a Red-Black tree based NavigableMap implementation.

Red-Black Tree – Ref- wiki
A red–black tree is a kind of self-balancing binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the color (red or black) of the node. These color bits are used to ensure the tree remains approximately balanced during insertions and deletions.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. For the TreeMap sorting to correctly work, the Keys should implement (internally or externally) the equals and hashcode methods correctly.

TreeMap is used where we need to store the data in a sorted order. Natural sorting of TreeMap is ascending order of the Keys, but you can change that using Comparators.

TreeMap example in Java

We will have a example with 2 TreeMaps – one with Keys as Integer and other with Keys as String. From the output you will be able to see the sorting done according to the Keys.

Output

TreeMap example in Java

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn