nervosol
nervosol

Reputation: 1291

Map of maps - putting value to inner map

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);
    }
}

Upvotes: 1

Views: 806

Answers (2)

Andrei Buneyeu
Andrei Buneyeu

Reputation: 6680

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)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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);
}

Upvotes: 4

Related Questions