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 妈妈生日祝福语简短励志