0

I have been studying leetcode problems and ran into one where I needed to increment the value of an existing key/value pair in a HashMap. I found the consensus was that the best way to do this in Java 8 is the following piece of code:

myMap.computeIfPresent(key, (k, v) -> v + 1);

In this example, why does v++ fail to work in place of v + 1?

Secondly, where might I go besides asking the question here to figure this out? I got the code to work but want to understand why my first instinct to put v++ doesn't.

Talenel
  • 422
  • 2
  • 6
  • 25
Efie
  • 1,430
  • 2
  • 14
  • 34
  • "fail to work"? What happened? A compile error? An exception? – khelwood Jul 20 '18 at 12:14
  • It compiled just fine but did not actually increment the value of v, which led to the code giving an incorrect answer – Efie Jul 20 '18 at 12:16
  • 1
    Because `v++` returns `v` and then increments it by `1`. `v + 1` immediately returns `v + 1`. there is a chance that `++v` would work just like `v + 1`. – EpicPandaForce Jul 20 '18 at 12:17

2 Answers2

3

The return value of v++ is the value of v before it was incremented.

Since the only thing that matters in this lambda is the return value, that would be equivalent of just using (k, v) -> v.

If you wanted to use a shorthand ++v would work, but v + 1 is clearer.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
1

v++ returns the previous value of v.

For example:

int v = 5;
int newValue = v++;
// newValue is now equal to 5

If your lambda function returns the old value of v, that's probably not what you intended.

If you had used ++v instead of v++ it might have done what you want, since ++v increments v and returns the new value.

But still, v+1 is clearer. Your lambda function is supposed to return one higher than v, not to increment v.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • To follow on this, why is only v + 1 necessary rather than v = v + 1? – Efie Jul 20 '18 at 12:23
  • 1
    @Efie: `v` is a local variable in your lambda (well, technically a parameter, but that behaves an awful lot like a local variable) . Modifying it does nothing, really. The only relevant part of that lambda is the value that it returns (which is implicitly the return value of the expression). – Joachim Sauer Jul 20 '18 at 12:27