使用鍵更新HashMap值Java程式


在本文中,我們將瞭解如何在Java中使用鍵更新HashMap的值。Java HashMap是基於雜湊表的Java的Map介面實現。它是一組鍵值對。

問題陳述

編寫一個程式,使用鍵更新HashMap的值。下面是相同的演示:

輸入

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

輸出

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

不同的方法

以下是使用鍵更新HashMap值的不同方法:

使用main()方法

以下是使用鍵更新HashMap值的步驟:

  • java.util包匯入HashMap
  • 在main方法中,建立一個HashMap名為input_map並新增鍵值對:“Java”=1,“Scala”=2和“Python”=3。
  • 列印原始HashMap。
  • 檢索與鍵“Scala”關聯的值,將其加10,然後更新input_map中的條目。
  • 列印包含更新值的HashMap

示例

在這裡,我們將所有操作繫結在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}

使用封裝

以下是使用封裝更新HashMap值步驟:

  • java.util包匯入HashMap
  • 定義一個靜態方法update,它接受一個HashMap和一個字串作為引數,以檢索指定鍵的值,將其加10,並更新HashMap中的條目,然後列印更新後的HashMap。
  • 在main方法中,建立一個HashMap名為input_map並新增鍵值對:“Java”=1,“Scala”=2和“Python”=3。
  • 列印原始HashMap。
  • 使用input_map和鍵“Scala”作為引數呼叫update方法。

示例

在這裡,我們將操作封裝到體現面向物件程式設計的函式中:

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}

更新於:2024年11月4日

658 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告