Reputation: 5730
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}}}
Upvotes: 0
Views: 476
Reputation: 4799
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.
Upvotes: 1
Reputation: 325
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.
Upvotes: 1
Reputation: 265
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());
Upvotes: 1