示例 1:使用 put() 更新 HashMap 值
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
numbers.put("Third", 3);
System.out.println("HashMap: " + numbers);
// return the value of key Second
int value = numbers.get("Second");
// update the value
value = value * value;
// insert the updated value to the HashMap
numbers.put("Second", value);
System.out.println("HashMap with updated value: " + numbers);
}
}
输出
HashMap: {Second=2, Third=3, First=1} HashMap with updated value: {Second=4, Third=3, First=1}
在上面的示例中,我们使用了 HashMap put() 方法来更新键 Second 的值。在这里,我们首先使用 HashMap get() 方法访问值。
示例 2:使用 computeIfPresent() 更新 HashMap 值
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
System.out.println("HashMap: " + numbers);
// update the value of Second
// Using computeIfPresent()
numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2);
System.out.println("HashMap with updated value: " + numbers);
}
}
输出
HashMap: {Second=2, First=1} HashMap with updated value: {Second=4, First=1}
在上面的示例中,我们使用 computeIfPresent()
方法重新计算了键 Second 的值。要了解更多信息,请访问 HashMap computeIfPresent()。
在这里,我们将 lambda 表达式用作方法的参数。
示例 3:使用 merge() 更新 HashMap 值
import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("First", 1);
numbers.put("Second", 2);
System.out.println("HashMap: " + numbers);
// update the value of First
// Using the merge() method
numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue);
System.out.println("HashMap with updated value: " + numbers);
}
}
输出
HashMap: {Second=2, First=1} HashMap with updated value: {Second=2, First=5}
在上面的示例中,merge()
方法将键 First 的旧值和新值相加。然后,将更新后的值插入 HashMap
。要了解更多信息,请访问 HashMap merge()。