gpt4 book ai didi

java - 如何让 ComputeIfPresent 在 Map 中与 Map 一起工作?

转载 作者:搜寻专家 更新时间:2023-10-30 19:57:03 28 4
gpt4 key购买 nike

当尝试使用 computeIfPresent() 方法更改 map 时,我在使用 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);

在第二个示例中,我收到以下错误消息:“lambda 表达式中的错误返回类型:整数无法转换为 Map<String, Integer>”。我的 IDE 将 v 识别为 Map。但是该功能不起作用。

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

我怎样才能让它工作?

最佳答案

外层 lambda 表达式应返回 v 引用的 Map:

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

它不能返回表达式 v.computeIfPresent(anotherKey, (x, y) -> y + 1); 的 Integer 值;

关于java - 如何让 ComputeIfPresent 在 Map 中与 Map 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980455/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com