Java程序从HashMap中删除键值对?

Java Program to remove key value pair from HashMap?

假设以下是我们的HashMap-

1
HashMap<String, String>map = new HashMap<String, String>();

将键值对添加到HashMap-

1
2
3
4
5
6
7
8
9
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()方法删除键值对-

1
map.remove("5");

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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);
   }
 }
}

输出量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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