Java.util.TreeMap中有contains()的兩個變體,本文都將進行討論。
1. containskey(Object o):如果映射包含指定鍵的映射,則返回true。
參數: o:The key which will be tested whether present or not. 返回值: Returns true if there is a mapping for the given key. Exception: ClassCastException:This is thrown if the given key cannot be compared with the keys currently in the map. NullPointerException:This is thrown if the specified key is null.
// Java code to demonstrate the working
// of containsKey()
import java.io.*;
import java.util.*;
public class containsKey {
public static void main(String[] args)
{
// Declaring the tree map of Integer and String
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
// assigning the values in the tree map
// using put()
treemap.put(2, "two");
treemap.put(7, "seven");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
// Use of containsKey
// returns true if mapping for the number is present
System.out.println(treemap.containsKey(6));
System.out.println(treemap.containsKey(4));
}
}
輸出:
true false
2. containsValue(Object o):如果此映射將一個或多個鍵映射到指定值,則返回true。
參數: o:This is the value whose presence in this map is to be tested. 返回值: Returns true if a mapping to this value exists else false. Exception: NA
// Java code to demonstrate the working
// of containsValue()
import java.io.*;
import java.util.*;
public class containsValue {
public static void main(String[] args)
{
// Declaring the tree map of Integer and String
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
// assigning the values in the tree map
// using put()
treemap.put(2, "two");
treemap.put(7, "seven");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
// Use of containsValue
// returns true if more than one keys are mapped
System.out.println(treemap.containsValue("six"));
System.out.println(treemap.containsValue("four"));
}
}
輸出:
true false
相關用法
- Java Map containsValue()用法及代碼示例
- Java ConcurrentHashMap containsValue()用法及代碼示例
- Java EnumMap containsValue(value)用法及代碼示例
- Java HashMap containsValue()用法及代碼示例
- Java TreeMap containsValue()用法及代碼示例
- Java Hashtable containsValue()用法及代碼示例
- Java WeakHashMap containsValue()用法及代碼示例
- Java IdentityHashMap containsValue()用法及代碼示例
- Java AbstractMap containsValue()用法及代碼示例
- Java ConcurrentSkipListMap containsValue()用法及代碼示例
- Java Properties containsValue(value)用法及代碼示例
- Java Java.util.function.BiPredicate用法及代碼示例
- Java Java.util.function.DoublePredicate用法及代碼示例
注:本文由純淨天空篩選整理自 Java.util.TreeMap.containskey() and containsValue() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。