从 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}

更新时间: 2019-07-30

491 流览量

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.