Map of Maps data structure

30,398

Solution 1

Map of maps is actually a tree-type structure without single root node (as well as map of maps of maps...).

You can look at Composite pattern which is widely used for implementing tree structures (if their components has the same type which is not the case as I feel).

Another solution is to implement a simple domain model. It'll be much clearer to read and easy to maintain something like:

school.getPupil ("John Doe").getMark ("Math")

than

school.get ("John Doe").get ("Math")

Solution 2

The regular Map collection works for this:

    Map<Object,Map<Object,Object>> mapOfMaps = new LinkedHashMap<Object,Map<Object,Object>>();
    Object newObject = new String("object as string");
    mapOfMaps.put(newObject, new LinkedHashMap<Object,Object>());
    Map<Object,Object> objectMap = mapOfMaps.get(newObject);

In fact, if you're not worried about type safety, you can put whatever you want into the value section:

    Map<Object,Object> mapOfWhatever = new LinkedHashMap<Object,Object>();
    Object newObject = new String("object as string");
    mapOfWhatever.put(newObject, new LinkedHashMap<Object,Object>());
    Map<Object,Object> objectMap = (Map<Object, Object>) mapOfWhatever.get(newObject);
Share:
30,398
Dónal
Author by

Dónal

I earn a living by editing text files. I can be contacted at: [email protected] You can find out about all the different kinds of text files I've edited at: My StackOverflow Careers profile

Updated on August 22, 2022

Comments

  • Dónal
    Dónal over 1 year

    The MultiValueMap class (Apache commons collections) makes it easy to work with a Map whose values are Collections. I'm looking for a a class that makes it easy to work with a Map whose keys are objects and values are Maps.

    I'm using Java 1.4, so can't use Google Collections or generics.

  • Andre Holzner
    Andre Holzner almost 11 years
    Typically one wants not to have to care about whether a given (first) key already is in mapOfMaps, e.g. when doing mapOfMaps.get("firstKey").put("secondKey",value). For example, Python's maps have a setdefault method for this purpose.