更新 HashMap 值的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用 put() 更新 HashMap 的值

import java.util.HashMap;

public 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;

public 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;

public 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()