📜  Java中的 SortedMap remove() 方法及示例

📅  最后修改于: 2022-05-13 01:55:29.111000             🧑  作者: Mango

Java中的 SortedMap remove() 方法及示例

Java中 SortedMap 接口的remove()方法用于从该映射中删除该键的映射(如果它存在于映射中)。

句法:

V remove(Object key)

参数:此方法具有唯一的参数,其映射将从映射中删除。

返回:此方法返回此SortedMap先前与键关联的值,如果 SortedMap 不包含键的映射,则返回 null。

注意:SortedMap 中的 remove() 方法继承自Java中的 Map 接口。

下面的程序说明了 remove() 方法的实现:

方案一:

Java
// Java code to show the implementation of
// remove method in SortedMap interface
 
import java.util.*;
 
public class GfG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initializing a SortedMap
        SortedMap map
            = new TreeMap<>();
        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);
    }
}


Java
// Java code to show the implementation of
// remove method in SortedMap interface
 
import java.util.*;
 
public class GfG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initializing a SortedMap
        SortedMap map
            = new TreeMap<>();
 
        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}
{1=One, 5=Five, 7=Seven, 9=Nine}

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

Java

// Java code to show the implementation of
// remove method in SortedMap interface
 
import java.util.*;
 
public class GfG {
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initializing a SortedMap
        SortedMap map
            = new TreeMap<>();
 
        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}

参考: https: Java/util/Map.html#put(K, %20V)