Java中的 ConcurrentHashMap containsValue() 方法
Java .util.concurrent.ConcurrentHashMap.containsValue()方法是Java中的一个内置函数,它接受一个值并在一个或多个键映射到指定值时返回 true。该方法遍历整个哈希表。因此,它是一个比 containsKey() 方法慢得多的函数。
句法:
chm.containsValue(Object val_element)
参数:该方法接受对象类型的单个参数val_element ,以检查它是否映射到映射中的任何键。
返回值:如果指定的val_element映射到此映射中的任何键,则该方法返回 true,否则返回 false。
异常:当指定的value_element为 null 时,函数会抛出 NullPointerException。
下面的程序说明了Java.util.concurrent.ConcurrentHashMap.containsValue()方法的使用:
程序 1:该程序涉及将整数值映射到字符串键。
/* Java Program to demonstrate containsValue()
method of ConcurrentHashMap */
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap chm =
new ConcurrentHashMap();
chm.put("Geeks", 120);
chm.put("for", 11);
chm.put("GeeksforGeeks", 15);
chm.put("Gfg", 50);
chm.put("GFG", 25);
// Check whether a key is mapped to 100
if (chm.containsValue(100)) {
System.out.println("100 is mapped.");
}
else {
System.out.println("100 is not mapped.");
}
// Check whether a key is mapped to 120
if (chm.containsValue(120)) {
System.out.println("120 is mapped.");
}
else {
System.out.println("120 is not mapped.");
}
}
}
输出:
100 is not mapped.
120 is mapped.
程序 2:该程序涉及将字符串值映射到整数键。
/* Java Program to demonstrate containsValue()
method of ConcurrentHashMap */
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap chm =
new ConcurrentHashMap();
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Gfg");
chm.put(104, "GFG");
// Check whether a key is mapped to Geeks
if (chm.containsValue("Geeks")) {
System.out.println("Geeks is mapped.");
}
else {
System.out.println("Geeks is not mapped.");
}
// Check whether a key is mapped to GfG
if (chm.containsValue("GfG")) {
System.out.println("GfG is mapped.");
}
else {
System.out.println("GfG is not mapped.");
}
}
}
输出:
Geeks is mapped.
GfG is not mapped.
参考: https: Java/util/concurrent/ConcurrentHashMap.html#containsValue()