English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此示例中,我们将学习使用键更新Java HashMap的值。
要理解此示例,您应该了解以下Java编程主题:
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); //返回键 Second 的值 int value = numbers.get("Second"); //更新值 value = value * value; //将更新的值插入到HashMap numbers.put("Second", value); System.out.println("Updated HashMap after value update: " + numbers); } }
Output result
HashMap: {Second=2, Third=3, First=1} Updated HashMap after value update: {Second=4, Third=3, First=1}
在上面的示例中,我们使用了HashMap put()方法来更新键为 Second 的值。在这里,首先,我们使用HashMap get()方法访问该值 。
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); // 更新Second的值 // 使用 computeIfPresent() numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2); System.out.println("Updated HashMap after value update: " + numbers); } }
Output result
HashMap: {Second=2, First=1} Updated HashMap after value update: {Second=4, First=1}
在上面的示例中,我们使用computeIfPresent()方法重新计算了键 Second 的值。要了解更多信息,请访问HashMap computeIfPresent().
在这里,我们将expression lambda用作该方法的方法参数。
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 Merge() method numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue); System.out.println("Updated HashMap after value update: " + numbers); } }
Output result
HashMap: {Second=2, First=1} Updated HashMap after value update: {Second=2, First=5}
In the above example, the merge() method adds the old value and new value of the key 'First'. And, the updated value is inserted into the HashMap. For more information, please visitHashMap merge().