Java 程式檢查 TreeMap 中是否存在特定值


要檢查 TreeMap 中是否存在特殊值,請使用 containsValue() 方法。

首先建立 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");

現在,假設我們需要檢查值“Java”是否存在。為此,請像這樣使用 containsValue() 方法 -

m.containsValue("Java")

以下是檢查 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 value PHP exist in the TreeMap = "+m.containsValue("Java"));    } }

輸出

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

更新日期:2019-07-30

259 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告