I have a HashMap
:
HashMap<string, Integer> hmap = new HashMap<>();
where I want to increase the HashMap value. In order to avoid the nullPointer Exception
if the key doesn't exist, I check it! Let's say the data are:
//201803271 - 1000
//201803271 - 1000
//201803272 - 1000
//inside a loop i read the data...
if (hmap.get("201803271") != null) {
hmap.put("201803271", hmap.get("201803271") + 1000);
}else{
hmap.put("201803271", 1000);
}
//end of loop
which works as I get:
201803271 - 2000
201803272 - 1000
But, I read this question How to update a value, given a key in a java hashmap? and there is a solution to use the Java 8 method getOrDefault
. I tried it
hmap.put("201803271", count.getOrDefault("201803271", 1000) + 1000)
However, with this solution I get wrong results...
201803271 - 3000
201803272 - 2000
What am I missing?
Java 8 introduced merge
method to Map
interface just for this type of problem:
hmap.merge("201803271", 1000, Integer::sum);
It means "put 1000 for this key but if this key already has a value add 1000 to it".
The reason your solution wasn't working is that you were getting 1000 by default and then adding 1000 to it. To do this correctly with getOrDefault
, you would want to replace 1000 with 0 in getOrDefault
. hmap.put("201803271", count.getOrDefault("201803271", 0) + 1000))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With