miikey722
miikey722

Reputation: 75

How to insert records into a Nested HashMap?

I want to create a nested HashMap of:

var myHashMap = new HashMap<String, HashMap<String, int>>();

And I want to insert records into the inner HashMap, I find myself needing to instantiate the inner HashMap if the key doesn't exist:

var myHashMap = new HashMap<String, HashMap<String, int>>();
var outerStringValue = "ABC";
var innerStringValue = "XYZ";
var innerInt = 45;

if (!myHashMap.containsKey(outerStringValue) {
    var innerHashMap = new HashMap<String, int>();
    innerHashMap.put(innerStringValue, innerInt);
    myHashMap.put(outerStringValue, innerHashMap);
} else {
    myHashMap.get(outerStringValue).put(innerStringValue, innerInt);
}

Is there a better way to do this without instantiating a new innerHashMap for each unique myHashMap (the outer HashMap) key?

Upvotes: 2

Views: 248

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29028

You can use Java 8 method computeIfAbsent(). It expects a key, a function that will be triggered and will generate a value if the given key is not present in the map.

Note that this method will return a value that is currently associated with the given key, i.e. a previously existing inner map, or a map generated as a result of the method execution.

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

nestedMap.computeIfAbsent(outerKey,k -> new HashMap<>())
    .put(innerKey, someValue);

Also note:

  • It's not possible to use primitives like int as a generic type parameters. Generic parameter should be an object (for more information, see)

Upvotes: 5

Related Questions