java.util.TreeMap stores Key Value pairs like
java.util.HashMap, and enables the retrieval of a Value given a Key. TreeMap differs from HashMap in that the Keys are ordered by their natural order. Internally the TreeMap maintains a Tree data structure, used to order and locate keys.
This tutorial, complete with an easy to understand and interactive UML visualization, explains how
This is the another instalment of our java.util.Map series. Earlier parts include:
- Hashmap Introduction Tutorial
- Hashmap and the Importance of HashCode
- Java 8, Map::computeIfAbsent Tutorial
Take a look at the Class Diagram above. You may note the following interesting points in this diagram:
java.util.SortedMap: All sorted maps, order keys by their natural ordering. E.g. natural ordering of strings would result in alphabetic ordering
java.lang.Comparable: this enables
PersonKeyinstances to be sorted. More specifically
java.lang.Comparable::compareTomethod. The method returns 0, if the
PersonKeyis equal to the object passed in. Alternatively
compareToshould return a positive integer if PersonKey is greater than the object passed in, or a negative integer should be returned.
Step through TreeMap in action
When the code is executed, the following is output. Note how the results have been ordered. Observe the
PersonKey::compareTo method and note how the last name is primarily used to order, and, secondarily, if the last names are equal, the first name is then used to order.
Last Name First Name Rating
Jackson Bill 2
Smith Andrew 1
Smith Bill 5
Smith Jack 4
Do you like this Codelytics’ visualization?
If you like our visualizations, be sure to subscribe to our mailing list below. With your free subscription, we will periodically send you alerts about new tutorials and visualizations posted here.