Java TreeMap remove()方法

java.util.TreeMap.remove() 从TreeMap中删除指定键的键值对。

1 语法

public V remove(Object key)

2 参数

key:这是应删除映射的key。

3 返回值

返回与key关联的先前值;如果没有key映射,则返回null。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.TreeMap.remove()方法的例子
 */
import java.util.*;

public class Demo {
    public static void main(String[] args) {

        // creating tree map
        TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

        // populating tree map
        treemap.put(2, "two");
        treemap.put(1, "one");
        treemap.put(3, "three");
        treemap.put(6, "six");
        treemap.put(5, "five");

        System.out.println("Value before modification: "+ treemap);

        // removing value at key 5
        System.out.println("Removed value: "+treemap.remove(5));
        System.out.println("Value after modification: "+ treemap);
    }
}

输出结果为:

Value before modification: {1=one, 2=two, 3=three, 5=five, 6=six}
Removed value: five
Value after modification: {1=one, 2=two, 3=three, 6=six}

热门文章

优秀文章