Java Check if key exists in HashMap

摘要: In Java, you can use Map.containsKey() to check if a key exists in a Map.

In Java, you can use Map.containsKey() to check if a key exists in a Map.

TestMap.java
package com.mkyong.examples;
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);
        fruits.put("watermelon", null);
        System.out.println("1. Is key 'apple' exists?");
        if (fruits.containsKey("apple")) {
            //key exists
            System.out.println("yes! - " + fruits.get("apple"));
        } else {
            //key does not exists
            System.out.println("no!");
        System.out.println("\n2. Is key 'watermelon' exists?");
        if (fruits.containsKey("watermelon")) {
            System.out.println("yes! - " + fruits.get("watermelon"));
        } else {
            System.out.println("no!");

Output

1. Is key 'apple' exists?
yes! - 1
2. Is key 'watermelon' exists?
yes! - null

References

  1. Java 7 Doc Map.containsKey

上一篇: Python How to loop a dictionary
下一篇: Python Whois client example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号