Java中的TreeMap containsValue()方法,附带示例
在Java中, TreeMap类 的 containsValue()方法 用于检查TreeMap中是否由任何键映射特定的值。它将该值作为参数,并在映射中的任何键映射该值时返回True。
--> java.util 包
--> TreeMap类
--> containsValue() 方法
语法:
Tree_Map.containsValue( _Object Value_ )
参数: 参数为 Object 类型的值,引用了需要通过地图中的任何键检查其映射的值。 (仅一参数)
返回类型: 一个布尔值,如果检测到该值的映射,则返回true,否则返回false。
注意: 在Java中,布尔值只能返回true或false,而非0和1,否则将在编译时抛出错误。
示例 1: 将字符串值映射到整数键。
//演示TreeMap类的containsValue()方法的Java程序
//引入必需的类
import java.util.*;
//主类
public class GFG {
//主驱动程序
public static void main(String[] args)
{
//通过将整数和字符串对的对象声明为对象创建一个空的TreeMap
TreeMap tree_map
= new TreeMap();
//使用put()方法将字符串值映射到int键
tree_map.put(10, "Geeks");
tree_map.put(15, "4");
tree_map.put(20, "Geeks");
tree_map.put(25, "Welcomes");
tree_map.put(30, "You");
//打印TreeMap的元素
System.out.println("Initial Mappings are: "
+ tree_map);
//使用containsValue()方法在映射中检查自定义值
//对于值'Geeks'
System.out.println(
"Is the value 'Geeks' present? "
+ tree_map.containsValue("Geeks"));
//检查值为“World”
System.out.println(
"Is the value 'World' present? "
+ tree_map.containsValue("World"));
}
}
输出结果
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Is the value 'Geeks' present? true
Is the value 'World' present? false
示例2: 将整数值映射到字符串键。
// Java程序演示TreeMap类的containsValue()方法
// 导入所需类
import java.util.*;
// 主类
public class GFG {
// 主方法
public static void main(String[] args)
{
// 创建一个空的TreeMap,声明字符串和整数对的对象
TreeMap tree_map
= new TreeMap();
// 使用put()方法将int值映射到字符串键
tree_map.put("Geeks", 10);
tree_map.put("4", 15);
tree_map.put("Geeks", 20);
tree_map.put("Welcomes", 25);
hastree_map_map.put("You", 30);
// 打印TreeMap的元素
System.out.println("初始映射为: " + tree_map);
// 使用containsValue()方法检查值'10'是否存在
System.out.println("值'10'是否存在? " + tree_map.containsValue(10));
// 检查值'30'是否存在
System.out.println("值'30'是否存在? " + tree_map.containsValue(30));
// 检查值'40'是否存在
System.out.println("值'40'是否存在? " + tree_map.containsValue(40));
}
}
输出:
注意: 同样,可以使用不同的数据类型进行变化和组合来执行任何类型的映射操作。