gpt4 book ai didi

java - 如何使用java中LinkedHashMap中特定键的旧值替换值

转载 作者:行者123 更新时间:2023-12-01 17:49:34 24 4
gpt4 key购买 nike

我有一个旧值存储在其中作为map{key,value}。我想通过对其执行计算来更新现有值,例如当它是整数时将值增加 10; map {键,值+10}

最佳答案

使用computeIfPresent (示例假设 Map<String, Integer> ):

map.computeIfPresent("key", (String key, Integer value) -> value + 10);

此方法允许您计算映射到给定键的新值。在上面的示例中,现有值将替换为 oldValue + 10 .

Map.computeIfPresent :

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

如果您需要更新插入,那么正确的使用方法是 merge ,如果键尚未与映射中的值关联,则插入:

map.merge("key", 1, (Integer oldValue, Integer newValue) -> oldValue + newValue);

在该示例中,1是要添加的新值,如果 "key" map 中不存在。如果"key"在 map 中不是新的,然后调用第三个参数中的函数来计算更新的值(在本例中,它将仅增加新值的值)。

关于java - 如何使用java中LinkedHashMap中特定键的旧值替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888826/

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