示例 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()。