使用该remove()
方法从TreeMap中删除一个值。
首先创建一个TreeMap并添加一些元素-
TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS");
现在,假设您需要使用键5删除一个值。为此,请使用remove()
方法-
Object ob = m.remove(5);
以下是从TreeMap中删除值的示例-
import java.util.*; public class Demo { public static void main(String args[]) { TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS"); System.out.println("TreeMap Elements..."); Collection res = m.values(); Iterator i = res.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println("TreeMap size = "+m.size()); //删除一个元素 Object ob = m.remove(5); System.out.println("\nTreeMap after removing a single element...\n "+m); System.out.println("Size of TreeMap now = "+m.size()); } }
输出结果
TreeMap Elements... PHP jQuery JavaScript Ruby Java AngularJS ExpressJS TreeMap size = 7 TreeMap after removing a single element... {1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 6=AngularJS, 7=ExpressJS} Size of TreeMap now = 6