Java程序,仅当键与给定值相关联时,才从HashMap中删除键
remove()仅当键与给定值相关联时,才使用该方法删除键。
假设以下是我们的HashMap-
//创建一个哈希映射
HashMap hm = new HashMap();
//将元素放入映射
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));在这里,仅当键“Belt”与给定值600相关联时,我们才将其删除-
hm.remove("Belt", 600);以下是仅在键与给定值关联时删除键的示例-
示例
import java.util.*;
public class Demo {
public static void main(String args[]) {
//创建一个哈希映射
HashMap hm = new HashMap();
//将元素放入映射
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("\nUpdated HashMap after删除键...");
System.out.println(hm);
//删除键 from a HashMap only if it is associated with a given value
hm.remove("Belt", 600);
System.out.println("\nUpdated HashMap after删除键 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删除键 associated with a given value...
{Frames=800, Bag=1100, Sunglasses=2000}热门推荐
10 高一祝福语简短 励志
11 立秋节气简短祝福语
12 简短公司周年祝福语大全
13 中考感言简短祝福语大全
14 体育老师简短祝福语
15 干杯生日祝福语简短独特
16 特别简短的祝福语老师
17 朋友坐车走了祝福语简短
18 给英雄的祝福语简短