Pujan
Pujan

Reputation: 3264

Fastest Way to Merge Multilevel HashMaps

I have many Multilevel HashMaps in which deepest element is List. Number of Levels may vary.

Intuitively lets say first hashmap is

{
    "com": {
        "avalant": {
            "api": []
        }
    }
}

and second hashmap is

{
    "com": {
        "google": {
            "service": {
                "api": []
            }
        }
    }
}   

After merge it should become

{
    "com": {
        "avalant": {
            "api": []
        },
        "google": {
            "service": {
                "api": []
            }
        }
    }
}

What is the best way to merge them ? Just iterate two maps at a time and combine would be good idea ?

Upvotes: 4

Views: 1743

Answers (1)

Absurd-Mind
Absurd-Mind

Reputation: 7994

I would first go with a version that really works, and after that see if I need a faster version.

A possible solution would be a recursive approach something like this (removed Generics and casts for easier read):

// after calling this mapLeft holds the combined data
public void merge(Map<> mapLeft, Map<> mapRight) {
    // go over all the keys of the right map
    for (String key : mapRight.keySet()) {
        // if the left map already has this key, merge the maps that are behind that key
        if (mapLeft.containsKey(key)) {
            merge(mapLeft.get(key), mapRight.get(key));
        } else {
            // otherwise just add the map under that key
            mapLeft.put(key, mapRight.get(key));
        }
    }
}

Just noticed the lambda label. I do not see a reason to use a stream here. Converting this to a stream would it make only more complicated in my opinion.

Upvotes: 6

Related Questions