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");
要删除键,请在此处设置键和相关值。如果存在关联值,则键将被删除-
m.remove(3, "Australia")
以下是一个仅在键与给定值相关联时从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("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}