Reputation: 23
I have a problem where when I want to change a value in a nested HashMap, the other HashMaps are being overwritten.
for example I have a key name Alligator, which stores a HashMap that contains the keys Weight and Size. I want to be able to change the value associated with Size, but not affect Weight at all. In a yml file, this is what it would look like.
Alligator:
Weight: 100.0
Size: 10.0
And this is what I would like to happen.
Alligator:
Weight: 150.0
Size: 10.0
This was Some Code that I found earlier that lets me change the values, but with overwriting...
HashMap< String, HashMap< String, Double>> data = new HashMap<>();
data.put("Alligator", new HashMap() {
{
put("Size", 10.0
}
});
HashMap< String, HashMap< String, Double>> data = new HashMap<>();
data.put("Alligator", new HashMap() {
{
put("Weight", 100.0
}
});
Upvotes: 2
Views: 1569
Reputation: 35
Crate a inner HashMap with different name, so you never get confused between two maps.
Map<String,Map<String,Integer>> outermap = new HashMap<String,Map<String,Integer>>();
Map<String,Integer> innermap1 = new HashMap<String,Integer>();
innermap1.put("Weight",100);
innermap1.put("Size", 10);
outermap.put("Alligator",innermap1);
Upvotes: 0
Reputation: 393771
data.put("Alligator", new HashMap() {
{
put("Weight", 100.0);
}
});
would overwrite the internal Map of the "Alligator" key if it's already in the outer Map.
You must check for existence first :
Map<String, Double> inner = data.get("Alligator");
if (inner != null) {
inner.put("Weight", 100.0);
} else {
data.put ("Alligator", new HashMap() {
{
put("Weight", 100.0);
}
});
}
BTW, I wouldn't use an anonymous sub-class of HashMap
instance for the inner Map.
You can replace it with this simpler code :
Map<String, Double> inner = data.get("Alligator");
if (inner == null) {
inner = new HashMap<>();
data.put ("Alligator",inner);
}
inner.put("Weight", 100.0);
Upvotes: 2
Reputation: 99
A
new HashMap(){ // blablabla
means a new Object instance in the memery,
and a
data.put("Alligator", new HashMap() { // blablabla
means adding(key not exists) or overwriting(key exists) a KV pair in the data map.
As @Eran suggests,
inner = data.get("Alligator")
checking if inner exists
Upvotes: 1
Reputation: 39287
First handle what you want to happen if there is no "Alligator" in your data HashMap
, possibly put in a new HashMap
for "Alligator":
if (!data.containsKey("Alligator")) {
data.put("Alligator", new HashMap<>());
}
Then use get
to grab the nested HashMap and use put
to change the values:
HashMap<String, Double> alligator = data.get("Alligator");
alligator.put("Weight", 150.0);
Upvotes: 1