I want to apply a compute method that increment value if key exists, otherwise puts 1. Having
Map<Integer, Integer> map = new HashMap<>();
I don't understand why
for (int i = 0; i < 10; i++) map.compute(1, (k, v) -> v != null ? v++ : 1);
results in {1=1}
and
for (int i = 0; i < 10; i++) map.compute(1, (k, v) -> (v != null ? v : 0) + 1);
results in {1=10}?
My understanding on first case is:
- if there's a value with key
k, get the result fromv++and put it back, else fill it with 1
While the seconds case is:
- if there's a value with k
ksavev+1instead, else save0+1, which is also 1
Why in this case running v++ doesn't result in v+1?