Java Map remove()方法及实例

Java Map remove()方法及实例

该方法用于从该地图中删除某个键的映射,如果该键存在于该地图中。

语法

V remove(Object key)

参数: 该方法有唯一的参数key,其映射要从地图中删除。
返回: 该方法返回该地图先前关联key的值,如果地图不包含key的映射,则返回null。
以下程序显示了int remove()方法的实现。

程序1 :

// Java code to show the implementation of
// remove method in Map interface
import java.util.*;
public class GfG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initializing a Map of type HashMap
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "One");
        map.put(3, "Three");
        map.put(5, "Five");
        map.put(7, "Seven");
        map.put(9, "Nine");
        System.out.println(map);
 
        map.remove(3);
 
        System.out.println(map);
 
        // If it doesn't exists, returns
        // null and does not affects the map
        map.remove(2);
 
        System.out.println(map);
    }
}

输出

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}

程序2: 下面的代码显示了put()的实现。

// Java code to show the implementation of
// remove method in Map interface
import java.util.*;
public class GfG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initializing a Map of type HashMap
        Map<String, String> map = new HashMap<>();
        map.put("1", "One");
        map.put("3", "Three");
        map.put("5", "Five");
        map.put("7", "Seven");
        map.put("9", "Nine");
        System.out.println(map);
 
        map.remove("3");
 
        System.out.println(map);
    }
}

输出

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
{1=One, 5=Five, 7=Seven, 9=Nine}

参考资料:
Oracle文档

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程