Search code examples
javacollectionsguavaapache-commons

how to easily access nested maps in java(or google guava)


I have a nested Hashmap (using JDK 7) as defined below

private static HashMap<SourceSystemIdEnum, HashMap<String, HashMap<StatsEnum, Double>>> statsCache = new HashMap<SourceSystemIdEnum, HashMap<String, HashMap<StatsEnum, Double>>>();

All the keys for all the maps (nested as well) are created at runtime and the value of outer map is another map; the values of next level of map is another map; and the value of inner most map is just a Double (it is not going to be collection).

I use above data structure to maintain cache (tree like object hierarchy) where the values of inner most map is updated every second (that is Double type).

I came across http://tomjefferys.blogspot.com/2011/09/multimaps-google-guava.html , while looking for a better/easier nested maps. But the value of inner most map is never going to be collection, so google Guava didnt seem relevant at first look(?)

I also came across this How to iterate through Nested Map and Multiset? - Java/Guava and even iteration doesnt be any better in guava (it seems).

I am trying to reduce routine (broiler plate) code when iterating or updating the values of my scenario (map within map within map) and how can I rewrite my existing code to switch to Google Guava's multimap (or is that going to be any better than regular hashmap of jdk7 ).

****EDIT**** I agree it is unusual to have such deep nesting. I can have a list of maps, but then lookup is going to be costly. Here is the breakdown of maps

HashMap : the outer map represents various data feeds as the keys(ex:NDAQ,CBOE,NYSE,AMEX)

HashMap the mid level map represents various tickers as the keys(ex:CSCO,INTC,MSFT..)

HashMap: the outer map represents values of various statistical parameters (EX: mean, median, skew,kurtosis) as the keys and it is these Double values that get updated every minute

NOTE: All the keys in above 3 maps are pretty much known in advance (so maps dont grow or resize during runtime-it is only Double value in inner most map that gets updated every minute)


Solution

  • It seems Trees is good data structure (as @Ata suggested). Because there is no standard JDK implementation of tree(??) and not convinced with adding open source tree implementations (from maven), I am going to stick with my existing nested maps. I will update this answer, if I find better solution