0

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

Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92

3 Answers3

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());
Seshidhar G
  • 265
  • 1
  • 9
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.

Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
1

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.

priyanka
  • 315
  • 3
  • 14