简体   繁体   中英

Java append `HashMap` values to existing HashMap if key matches

I have below HashMap(to.String()) printed below.

HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();

HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}

I want to append {group={iterate=1}} to existing map if key disabled matches.

Finally my map should look like below, how can I achieve it?

HashMap abc = {disabled={account={testConfiguration=1, iterate=1}, {group={iterate=1}}}

Here is the example for your desired output disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}

HashMap<String, Integer> accountmap = new HashMap<>();
    HashMap<String, Integer> groupMap = new HashMap<>();
    HashMap<String, HashMap<String, Integer>> disableMap = new HashMap<>();
    HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
    accountmap.put("testConfiguration",1);
    accountmap.put("iterate",1);
    disableMap.put("account",accountmap);
    abc.put("disabled", disableMap);
    if(abc.containsKey("disabled")){
        groupMap.put("iterate", 1);
        disableMap.put("group",groupMap);
    }
    System.out.println(abc.entrySet());

I think you want this:

abc.computeIfPresent("disabled", (k,v) -> {
    v.put("group", yourValue);
    return v;
});

or simply:

if (abc.containsKey("disabled")) {
    abc.get("disabled").put("group", yourValue);
}

I personally prefer the first approach, since it's a bit faster and works properly with concurrent maps.

The below code gives you the hashmap in the following format {disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}}

public static void main(String []args) {
    HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();

    // HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
    HashMap<String, Integer> thirdHash = new HashMap<>();
    thirdHash.put("testConfiguration", 1);
    thirdHash.put("iterate", 1);

    HashMap<String, HashMap<String, Integer>> secondHash = new HashMap<>();
    secondHash.put("account", thirdHash);

    abc.put("disabled", secondHash);

    // append {group={iterate=1}}

    HashMap<String, Integer> appendFirst = new HashMap();
    appendFirst.put("iterate", 1);
    if (abc.containsKey("disabled")) {
        abc.get("disabled").put("group", appendFirst);
    }

    System.out.println(abc);
}

Happy Coding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM