您的位置:首页 > 编程语言 > Java开发

Java – Check if key exists in HashMap

2015-09-29 10:05 363 查看
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

“`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: