Reputation: 39
I want to create a Map which is contains another map.If there is no special key in inner Map, I want to create that key with value= 1, otherwise increment its value.
I wrote this code :
Map <String, Map <String,Double>> ingMap= new HashMap<>();
Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
ingMap.put("A", k);
k.put("Class2", 1.0);
ingMap.put("A", k);
k.put("Class1", 1.0);
ingMap.put("B", k);
k.put("Class2", 1.0);
ingMap.put("B", k);
k = ingMap.get("A");
if (k.containsKey("Class3")) {
k.put("Class3", k.get(k)+1);
ingMap.put("A", k );
}
else{
k.put("Class3", 1.0);
ingMap.put("A",k );
}
System.out.println("\n" + ingMap);
The result is:
{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0, **Class3=1.0}**}
But really I wanted :
{A={Class1=1.0, Class2=1.0, Class3=1.0}, B={Class1=1.0, Class2=1.0}}
Upvotes: 0
Views: 2471
Reputation: 393936
You are putting the same inner map k
in all the values of the outer map.
You need to create a new inner map instance for each outer map key :
Map <String,Double> k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("A", k);
k= new HashMap<>();
k.put("Class1", 1.0);
k.put("Class2", 1.0);
ingMap.put("B", k);
And there's no need to put the same value with the same key twice, as it does nothing.
And the code for updating the inner map should be like this :
k = ingMap.get("A");
if (k != null) {
if (k.containsKey("Class3")) {
k.put("Class3", k.get("Class3")+1);
}
else {
k.put("Class3", 1.0);
}
}
Upvotes: 1