使用该remove()方法从TreeMap中删除键。
让我们首先创建一个TreeMap并添加一些元素-
TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"India"); m.put(2,"US"); m.put(3,"Australia"); m.put(4,"Netherlands"); m.put(5,"Canada");
现在让我们删除键。在这里,我们现在要删除键3-
m.remove(3)
以下是从TreeMap中删除键的示例-
import java.util.*;
public class Demo {
public static void main(String args[]) {
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");
System.out.println("TreeMap Elements = "+m);
System.out.println("Removing a Key = "+m.remove(3));
System.out.println("Updated TreeMap Elements = "+m);
}
}输出结果
TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Removing a Key = Australia
Updated TreeMap Elements = {1=India, 2=US, 4=Netherlands, 5=Canada}