Java 更新HashMap中键对应的值

Java 更新HashMap中键对应的值

在本文中,我们将了解如何通过键更新HashMap中的值。Java HashMap是Java Map接口的基于哈希表的实现。它是一组键值对的集合。

下面是一个示例:

假设我们的输入是

Input HashMap: {Java=1, Scala=2, Python=3}

期望的输出将是

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

步骤

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 – Create a hashmap of values and initialize elements in it using the ‘put’ method.
Step 5 - Display the hashmap on the console.
Step 6 - To fetch a specific value, access the hashmap using the key, with the ‘get’ method.
Step 7 - Add certain value to the fetched value.
Step 8 - Display the updated value on the console.
Step 9 - Stop

示例1

在这里,我们将所有操作绑定在‘main’函数下。

import java.util.HashMap;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      int value = input_map.get("Scala");
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
}

输出

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

示例2

在这里,我们将操作封装成展示面向对象编程的函数。

import java.util.HashMap;
public class Demo {
   static void update(HashMap<String, Integer> input_map, String update_string){
      int value = input_map.get(update_string);
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      String update_string = "Scala";
      update(input_map, update_string);
   }
}

输出

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程