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 TreeMap
works.
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
Class Diagram
Take a look at the Class Diagram above. You may note the following interesting points in this diagram:
java.util.TreeMap
implementsjava.util.SortedMap
: All sorted maps, order keys by their natural ordering. E.g. natural ordering of strings would result in alphabetic orderingPersonKey
implementsjava.lang.Comparable
: this enablesPersonKey
instances to be sorted. More specificallyPersonKey
implements thejava.lang.Comparable::compareTo
method. The method returns 0, if thePersonKey
is equal to the object passed in. AlternativelycompareTo
should 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
Step through the visualisation from the above image, and read the yellow comments and the associated code.
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.
Leave a Reply