仅当键与给定值关联时,Java 程序从 TreeMap 中移除键


仅当 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");

要移除一个键,请在这里设置键和关联值。如果关联值存在,则移除键 -

m.remove(3, "Australia")

以下是仅当 TreeMap 中的键与给定值相关联时,才从 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);
      // removing a key associated with a given value
      System.out.println("Key removed? "+m.remove(3, "Australia"));
      System.out.println("Updated TreeMap Elements = "+m);
   }
}

输出

TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Key removed? true
Updated TreeMap Elements = {1=India, 2=US, 4=Netherlands, 5=Canada}

更新于: 30-Jul-2019

112 次浏览

职业生涯启动

通过完成课程获取认证

开始
广告
© . All rights reserved.