HierarchicalMap Tutorial - Intermediate Level
HierarchicalMap is an interface. So anyone can implement it. This tutorial is based on BasicHierarchicalmap, a reference implementation of HierarchicalMap.
Following subjects are covered in this tutorial:
Basic Level1. Getting Started
The HierarchicalMap interface is composed by three main sets of methods and some helper methods:
Following is our first sample code:
As you can see, HierarchicalMap behaves exactly like HashMap when simple key is used.2. Creating Structure
Now, we can create a more complex structure:
Each circle, or node, represents an instance of HierarchicalMap and the rectangle, or leaf, represents any other objects. A node can map subsequent nodes (this is the case of "Order" and "Address"), or can map leaves, e.g. java.lang.String, (this is the case of "type", "City", "State" and "Zip Code").
The following snippet of code will create a data structure representing the data shown above:
The method "add" also has another signature in which it receives only the "key" and return an empty map appended under that "key". Then, the second address can be added using the following code instead:3. Recovering the Data
Once the structure is filled, you can query the data inside:
The lines above will produce the following output:
Sta Clara SP
Note that the get operation will recover a single data, which we stipulated to be the first data inserted. So even having two cities in the structure, the first one (Sta Clara) was retrieved in the example above. On the other hand, the return for the state was SP because we retrieved the first state from address2 node. If you need to obtain entire set of objects with same key you should use getAll instead:
The code above will produce the following output:
Sta Clara São Paulo4. Interacting with Collections
Iterating with the structure will give the most intersting result:
This will produce the following output:
Address type : Billing City : Sta Clara State : CA ZIP code : 95054 Address type : Shipping City : São Paulo State : SP ZIP code : 04717-0045. Restructuring the Map
Although the structure used so far is in conformation with XSD recommendation, it is not possible to take advantage of HierarchicalMap. Information organized in such way, does not allow the direct access to inner data (e.g. get the shipping State). This "direct access" can be achieved with a little restructuring on the HierarchicalMap. Thus, we can implement a following method for instance:
With the above method, we can transform the original map to the following structure:
Now, we can query the map like this:
The result will be:
Shipping State: SP Billing State: CA
The following method can be written to reorganize the map back to the original structure:
Actually, this is all about HierarchicalMap. As you can see, it is as simple as that.
Though, there are many intersting and sometimes complex application for this simple interface.
Continue to Intermediate Level