從 Java 中的 TreeMap 中移除鍵
使用 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}
廣告