Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a hashmap value, given a key with getOrDefault

Tags:

hashmap

java-8

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?

like image 643
yaylitzis Avatar asked Jan 29 '23 04:01

yaylitzis


1 Answers

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

like image 53
Misha Avatar answered Feb 16 '23 16:02

Misha