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 婚前女儿生日祝福语简短