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

别说谁变了你拦得住时间么 提交于 2020-01-25 08:11:06

问题


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


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/59320796/java-append-hashmap-values-to-existing-hashmap-if-key-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!