僅在鍵與給定值關聯的情況下,從此 HashMap 中移除鍵的 Java 程式
僅當鍵與給定值關聯時,才使用 remove() 方法來移除鍵。
假設以下內容是我們 HashMap −
// 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));在此,我們僅在與給定值 600 關聯的情況下,才刪除鍵“Belt” −
hm.remove("Belt", 600);以下是僅在鍵與給定值關聯的情況下,移除鍵的一個示例 −
示例
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);
// removing a key
hm.remove("Wallet");
System.out.println("
Updated HashMap after removing a key...");
System.out.println(hm);
// removing a key from a HashMap only if it is associated with a given value
hm.remove("Belt", 600);
System.out.println("
Updated HashMap after removing a key associated with a given value...");
System.out.println(hm);
}
}輸出
Elements in HashMap...
[Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000]
Updated HashMap after removing an key...
[Frames=800, Belt=600, Bag=1100, Sunglasses=2000]
Updated HashMap after removing a key associated with a given value...
{Frames=800, Bag=1100, Sunglasses=2000}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP