僅當鍵與給定值關聯時,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.