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...
"+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

更新於: 2019 年 7 月 30 日

130 次觀看

啟動你的 職業生涯

透過完成課程獲得認證

馬上開始
廣告