要从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));
现在让我们删除一个键-
hm.remove("Wallet");
以下是从HashMap中删除键的示例-
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 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}