Java程式:從HashMap中移除鍵


在這篇文章中,我們將學習如何從HashMap中移除一個特定的鍵值對。Java。透過這樣做,我們可以動態更新對映的內容,這在許多資料操作場景中非常有用。

我們將演示兩種不同的方法:一種使用簡單的remove()方法刪除特定鍵,另一種利用迭代器在迭代時根據條件查詢並刪除鍵。每種方法都允許我們根據不同的需求有效地管理HashMap中的資料。

問題陳述

給定一個包含鍵值對的HashMap,編寫Java程式來移除一個特定的鍵:

輸入

Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

輸出

Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

Updated HashMap after removing a key...
{Frames=800, Belt=600, Bag=1100, Sunglasses=2000}

不同的方法

以下是從HashMap中移除鍵的不同方法:

使用remove()方法

以下是使用remove()方法從HashMap中移除鍵的步驟:

  • 首先,我們將匯入java.util包中的所有類。
  • 我們初始化HashMap並新增幾個鍵值對,其中每個專案都表示一個物件(如“包”或“錢包”)以及相關的價格。
  • 在移除任何項之前,我們將列印HashMap的初始內容以顯示所有鍵值對。
  • 使用HashMap類的remove()方法,我們刪除HashMap中鍵為"Wallet"的條目。
  • 移除鍵後,我們將再次列印HashMap以顯示更新後的內容,其中不包含"Wallet"條目。

示例

以下是從HashMap中移除鍵的示例:

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      System.out.println("Elements in HashMap...");
      System.out.println(hm);
      hm.remove("Wallet");
      System.out.println("
Updated HashMap after removing a key..."); System.out.println(hm); } }

輸出

Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]

Updated HashMap after removing a key...
{Frames=800, Belt=600, Bag=1100, Sunglasses=2000}

使用迭代器

以下是使用迭代器從HashMap中移除鍵的步驟:

  • 首先,我們將從java.util包匯入HashMapIteratorMap類
  • 我們將初始化HashMap並新增鍵值對。
  • 我們將使用迭代器迴圈遍歷HashMap。
  • 為了在迭代時滿足特定條件時移除鍵,我們將使用if語句
  • 列印移除前後的HashMap。

示例

以下是從HashMap中移除鍵的示例:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        // Creating a HashMap
        HashMap<String, Integer> map = new HashMap<>();
        
        // Adding elements to HashMap
        map.put("Apple", 100);
        map.put("Banana", 150);
        map.put("Grapes", 200);
        
        System.out.println("Original Map: " + map);
        
        // Using an iterator to remove a key
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Integer> entry = iterator.next();
            if (entry.getKey().equals("Banana")) {
                iterator.remove();  // Removes "Banana" from the map
            }
        }
        
        System.out.println("Updated Map after iterator removal: " + map);
    }
}

輸出

Original Map: {Apple=100, Grapes=200, Banana=150}
Updated Map after iterator removal: {Apple=100, Grapes=200}

更新於:2024年11月7日

548 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告