4

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?

yaylitzis
  • 5,354
  • 17
  • 62
  • 107

2 Answers2

5

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Misha
  • 27,433
  • 6
  • 62
  • 78
5

You could do it like this:

map.put(key, map.getOrDefault(key, 0) + inc);

or

map.compute(key, (k, v) -> v == null ? inc : v + inc);
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35