Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ComputeIfPresent working with Map within Map?

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?

like image 645
Yves Viegen Avatar asked Apr 23 '18 11:04

Yves Viegen


1 Answers

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

like image 114
Eran Avatar answered Sep 28 '22 09:09

Eran