Java程序从HashMap中删除键值对?
假设以下是我们的HashMap-
HashMap<String, String>map = new HashMap<String, String>();
将键值对添加到HashMap-
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "D");
map.put("5", "E");
map.put("6", "F");
map.put("7", "G");
map.put("8", "H");
map.put("9", "I");现在,使用该remove()方法删除键值对-
map.remove("5");示例
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
HashMap<String, String>map = new HashMap<String, String>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
map.put("4", "D");
map.put("5", "E");
map.put("6", "F");
map.put("7", "G");
map.put("8", "H");
map.put("9", "I");
System.out.println("HashMap...");
for (String res: map.keySet()) {
System.out.println(res);
}
map.remove("5");
System.out.println("Updated HashMap...");
for (String res: map.keySet()) {
System.out.println(res);
}
map.remove("8");
System.out.println("Updated HashMap...");
for (String res: map.keySet()) {
System.out.println(res);
}
}
}输出结果
HashMap... 1 2 3 4 5 6 7 8 9 Updated HashMap... 1 2 3 4 6 7 8 9 Updated HashMap... 1 2 3 4 6 7 9
热门推荐
10 生日祝福语 简短独特老弟
11 简短朋友旅行祝福语大全
12 新年简短的祝福语爱情
13 学生节祝福语大全简短
14 生日祝福语大全女孩简短
15 职场祝福语大全 简短精辟
16 生病祝福语简短文案
17 拜年祝福语 简短句子
18 新年祝福语简短给孩子