gpt4 book ai didi

java - 为什么map.merge()不是每次都调用remapping函数?

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:59 24 4
gpt4 key购买 nike

Map.merge() 文档说:

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping.

例如,这段代码应该计算篮子里每种水果的数量:

public static void main(String[] args) {
Map<String, Integer> fruitCounts = new HashMap<>();
List<String> fruitBasket = Arrays.asList(
"Apple", "Banana", "Apple", "Orange", "Mango", "Orange", "Mango", "Mango");
for (String fruit : fruitBasket) {
fruitCounts.merge(fruit, 1/*First fruit of this type*/, (k, v) -> v + 1);
}
System.out.println(fruitCounts);
}

有 2 个苹果、3 个芒果、2 个橙子和 1 个香蕉,但实际输出是:

{Apple=2, Mango=2, Orange=2, Banana=1}

怎么了?

最佳答案

问题就在这里

(k, v) -> v + 1

你应该做的

(k, v) -> k + v

如果你检查合并的实现,它说,remappingFunction.apply(oldValue, value); 意味着现有值将是第一个参数,你应该在其中添加与初始化它相同的数字作为该函数的第二个参数。

更新

关于java - 为什么map.merge()不是每次都调用remapping函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071088/

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