When trying to alter a Map using the computeIfPresent() method I have trouble implementing this method when I use an innerMap.
This works:
Map<String, Integer> mapOne = new HashMap<>();
mapOne.computeIfPresent(key, (k, v) -> v + 1);
This doesn't work:
Map<String, Map<String, Integer>> mapTwo = new HashMap<>();
mapTwo.computeIfPresent(key, (k, v) -> v.computeIfPresent(anotherKey, (x, y) -> y + 1);
In the second example I get the following error message: "Bad return type in lambda expression: Integer cannot be converted to Map<String, Integer>
".
My IDE recognizes v as a Map. But the function doesn't work.
Apparently the method returns an Integer, but I fail to see how this differs from the first method with no Innermap. So far I haven't found a similar case online.
How can I get this to work?
The outer lambda expression should return the Map
referenced by v
:
mapTwo.computeIfPresent(key,
(k, v) -> {
v.computeIfPresent(anotherKey, (x, y) -> y + 1);
return v;
});
It cannot return the Integer
value of the expression v.computeIfPresent(anotherKey, (x, y) -> y + 1);
.
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