1

I have map of maps

Map<String, Map<String,Integer>> outerMap = new HashMap<String, Map<String, Integer>>();

and I want to put some values to inner map. Is that correct way? Or it can be done better?

class SampleMap {
    Map<String, Map<String, Integer>> outerMap = new HashMap<String, Map<String, Integer>>();

    public void add(String outerKey, String innerKey, Integer value) {
        Map<String, Integer> tempMap = new HashMap<String, Integer>();
        if (outerMap.size() > 0)
            tempMap = outerMap.get(outerKey);
        tempMap.put(innerKey, value);
        outerMap.put(key, tempMap);
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
nervosol
  • 1,295
  • 3
  • 24
  • 46

2 Answers2

4

You can improve the code by avoiding the creation of a new inner map eagerly, until the point when you know that you must create it.

In addition, if you know that the inner map instance came from the outer map, you don't have to spend time putting it back where it came from.

public void add(String outerKey, String innerKey, Integer value) {
    Map<String, Integer> tempMap
    if (outerMap.containsKey(outerKey)) {
        tempMap = outerMap.get(outerKey);
    } else {
        tempMap = new HashMap<String, Integer>();
        outerMap.put(outerKey, tempMap);
    }
    tempMap.put(innerKey, value);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Technically there is nothing wrong in your code (except a minor improvement suggested by dasblinkenlight), but is map of maps what you really need?

If you want to read/write values by two keys, probably it's better to create map from pair of two keys (MultiKey or Pair implementation can be used) or another data structure (see this comment for details https://stackoverflow.com/a/3093993/554281)

Community
  • 1
  • 1
Andrei Buneyeu
  • 6,662
  • 6
  • 35
  • 38