Explain java map of maps.
in the project I am currently working on we had three different types of prices depending on the age of the user (adult, child, etc...). So we had on the DB a table looking like this:
PRICES
type Amount
A 20
B 15
C ..
D ..
At first we only had 4 different types of prices, so in the code, we had something like this: Map
Where the keys were the price type.
Recently, they added a new business rule that adds 3 subtypes to every price type, so now we have something like this:
PRICES
type subtype Amount
A 1 20
A 2 15
A 3 ..
B 1 ..
B 2 ..
... .. ..
Which of the following two options do you think is better and why?
Nested Maps
Map
where the keys are the price type and subtype:
prices.get(type).get(subtype);
Combined Keys
The same map than originally:
Map
And concatenate the keys to index the different prices:
prices.get(type+"_"+subtype);
Regarding the Java map of maps - Both nested and combined keys have their places. bowmore gives a pro argument for composite keys, and a con argument for nested maps. Let me provide the loyal opposition:
Composite map keys work great when you're looking up a specific known item.
Nested maps work well when you need to rapidly find all the variations, kinds, and subtypes of type A. For example, choosing A (vs. B, C, ...) might be the first step in a decision tree. Once the user or algorithm or whatever picks A, then you need to know only about A's subtypes, and B..Z or B..ZZZZZ no longer matter.
Now you're dealing with a very tight and efficient lookup structure for the subsearch. If you try to do that with composite keys, you end up doing a full table scan a la [ (key, value) for (key, value) in prices.items() if key.startswith('A') ]. That's not an efficient operation, and will be slow if the map is at all large.
Nested maps also work well when the number of nesting levels may grow. The problem structure already extended from type to (type, subtype). Is there any chance the next rev will need (type, subtype, variation) or (type, subtype, version)? If so, a nested mapping approach can be cleanly extended. This, however, is a stylistic, second-order advantage, especially compared to the "easy subsearch" advantage above.