Java教程

Java 使用 key 更新 HashMap 值的程序

使用key更新HashMap值的Java程序

在这个例子中,我们将学习使用key来更新Java HashMap的值。
要理解此示例,您应该了解以下Java 编程主题:
Java HashMap Java Lambda 表达式

示例 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()。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4