Java 如何让ComputeiPresent在Map中使用Map?

Java 如何让ComputeiPresent在Map中使用Map?,java,dictionary,hashmap,Java,Dictionary,Hashmap,当尝试使用computeIfPresent()方法更改映射时,我在使用innerMap时无法实现此方法 这是有效的: Map<String, Integer> mapOne = new HashMap<>(); mapOne.computeIfPresent(key, (k, v) -> v + 1); Map<String, Map<String, Integer>> mapTwo = new HashMap<>(); map

当尝试使用computeIfPresent()方法更改映射时,我在使用innerMap时无法实现此方法

这是有效的:

Map<String, Integer> mapOne = new HashMap<>();
mapOne.computeIfPresent(key, (k, v) -> v + 1);
Map<String, Map<String, Integer>> mapTwo = new HashMap<>();
mapTwo.computeIfPresent(key, (k, v) -> v.computeIfPresent(anotherKey, (x, y) -> y + 1);
Map-mapOne=newhashmap();
计算呈现(键,(k,v)->v+1);
这不起作用:

Map<String, Integer> mapOne = new HashMap<>();
mapOne.computeIfPresent(key, (k, v) -> v + 1);
Map<String, Map<String, Integer>> mapTwo = new HashMap<>();
mapTwo.computeIfPresent(key, (k, v) -> v.computeIfPresent(anotherKey, (x, y) -> y + 1);
Map-maptow2=newhashmap();
mapTwo.ComputeiPresent(key,(k,v)->v.ComputeiPresent(另一个key,(x,y)->y+1);
在第二个示例中,我得到以下错误消息:“lambda表达式中的错误返回类型:Integer无法转换为
Map
”。 我的IDE将v识别为一个映射,但该函数不起作用

显然,该方法返回一个整数,但我看不出这与没有Innermap的第一个方法有何不同。到目前为止,我还没有在网上找到类似的情况


如何使其工作?

外部lambda表达式应返回由
v
引用的
Map

mapTwo.computeIfPresent(key, 
                        (k, v) -> {
                                v.computeIfPresent(anotherKey, (x, y) -> y + 1); 
                                return v;
                            });

它不能返回表达式
v.computeIfPresent(另一个键,(x,y)->y+1);

为了了解您的问题,让我们看看您正在使用的方法的签名:

V computeIfPresent(K键,双功能有点离题(有点),但对同一张地图做同样的事情,以神秘的方式中断:

// breaks with ConcurrentModificationException
Map<String, Integer> test = new HashMap<>(); // or  = new Hashtable<>();
test.computeIfAbsent("one", x -> test.computeIfAbsent("one", y -> 1));

// IllegalStateException: Recursive update
Map<String, Integer> test = new ConcurrentHashMap<>();
// ... same code

// the only one that works correctly that I am aware of
Map<String, Integer> test = new ConcurrentSkipListMap<>();
//使用ConcurrentModificationException中断
Map test=new HashMap();//或=new Hashtable();
test.computeIfAbsent(“一”,x->test.computeIfAbsent(“一”,y->1));
//IllegalStateException:递归更新
映射测试=新的ConcurrentHashMap();
//…相同的代码
//我所知道的唯一一个工作正常的
映射测试=新的ConcurrentSkipListMap();

在第一个示例中,映射类型为
,因此lambda函数返回和整数是正确的。但是,在第二个示例中,映射类型为
,因此lambda函数应返回映射..而不是整数。