Java – Check if key exists in HashMap
来源:互联网 发布:计算圆周率算法 编辑:程序博客网 时间:2024/06/16 12:34
In Java, you can use the Map.containsKey()
method to check if a key exists in a Map
.
TestMap.java
package com.mkyong.test;import java.util.HashMap;import java.util.Map;public class TestMap { public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); if(fruits.containsKey("apple")){ //key exists System.out.println(fruits.get("apple")); }else{ //key not exists } }}···Output···1···Alternatively, just check the `null` value like this :###`TestMap.java`
package com.mkyong.test;
import java.util.HashMap;
import java.util.Map;
public class TestMap {
public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); Integer appleQty = fruits.get("apple"); if(appleQty!=null){ //key exists System.out.println(appleQty); }else{ //key not exists }}
}
Output
1
“`
0 0
- Java – Check if key exists in HashMap
- Python – Check if key exists in dictionary
- check if filed exists in all tables in current DB
- Check if a table or field exists in a database
- Makefile – Check if a file exists using wildcard function
- Ant Task check if a file exists
- How to check if a Number is Positive or Negative in Java - Interview Question
- How to Check if an Array Contains a Value in Java Efficiently?
- Java HashMap 判断 Key 相等
- DROP TABLE IF EXISTS” in Oracle and SQL Server
- DROP TABLE IF EXISTS” in Oracle and SQL Server
- “DROP TABLE IF EXISTS” in Oracle and SQL Server
- MySQL—— Insert record if not exists in table
- LoadRunner报这个错:invalid application path!please check if application exists
- hashmap in java
- Thinking In Java:HashMap
- Implement HashMap in Java
- hashmap in java : )
- leetcode之路050 Pow(x, n)
- ycmsmocbpbgq
- 写下常用的正则(regular expression)
- pm2.5接口,城市pm2.5指数查询接口调用代码示例
- arm+linux交叉编译libxml2
- Java – Check if key exists in HashMap
- Android自定义解析Html的TextView-HtmlView
- 程序员面试、算法研究、编程艺术、红黑树、数据挖掘5大系列集锦
- js实现用户输入的小写字母自动转大写字母
- svn本地资源异常
- 41. PHP MySQL 连接数据库
- C++ string::push_back
- Swift数据类型-可选类型
- 虚拟机VMware Workstation 提示cannot connect to the virtual machine.