Java程序来检查TreeMap中是否存在特定键

若要检查TreeMap中是否存在特定键,请使用containsKey()方法。

首先创建一个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是否存在。为此,设置这样的containsKey()方法-

m.containsKey(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...\n"+m);
      System.out.println("Does key 5 exist in the TreeMap = "+m.containsKey(5));
   }
}

输出结果

TreeMap Elements...
{1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS}
Does key 5 exist in the TreeMap = true