# Java - 从`HashMap`中删除映射

> 原文： [https://beginnersbook.com/2014/07/java-remove-mapping-from-hashmap-example/](https://beginnersbook.com/2014/07/java-remove-mapping-from-hashmap-example/)

#### 示例

在这个例子中，我们将看到如何使用键值对的键值从[`HashMap`](https://beginnersbook.com/2013/12/hashmap-in-java-with-example/)中删除特定的映射。我们将使用以下`HashMap`类方法来执行此操作：

`public Value remove(Object key)`：从此映射中移除指定键的映射（如果存在），并返回该特定键的元素值。更多关于[`remove`方法 Javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#remove(java.lang.Object))。

**完整代码：**

```java
import java.util.HashMap;

public class RemoveMappingExample {

 public static void main(String[] args) {

    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();

    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Value1");
    hashmap.put(22,"Value2");
    hashmap.put(33,"Value3");
    hashmap.put(44,"Value4");
    hashmap.put(55,"Value5");
    hashmap.put(66,"Value6");

    // Displaying HashMap Elements
    System.out.println("HashMap Elements: " + hashmap);

    // Removing Key-Value pairs for key 33
    Object removedElement1 = hashmap.remove(33);
    System.out.println("Element removed is: " +removedElement1);

    // Removing Key-Value pairs for key 55
    Object removedElement2 = hashmap.remove(55);
    System.out.println("Element removed is: " +removedElement2);

    // Displaying HashMap Elements after remove
    System.out.println("After Remove:");
    System.out.println("--------------");
    System.out.println("HashMap Elements: " + hashmap);
 }
}
```

**输出：**

```java
HashMap Elements: {33=Value3, 55=Value5, 66=Value6, 22=Value2, 11=Value1, 44=Value4}
Element removed is: Value3
Element removed is: Value5
After Remove:
--------------
HashMap Elements: {66=Value6, 22=Value2, 11=Value1, 44=Value4}

```