Java – Check if key exists in HashMap

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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
mkyongJava Programmer Recent comment authors
newest oldest most voted
Java Programmer
Guest
Java Programmer

Incorrect. “get” will return null if the key exists and maps to null or if the key does not exist. “getEntry” will return null only if the key does not exist.

mkyong
Guest
mkyong

Thanks for your inputs, article is updated. To avoid confusion, it is better stay with the proven Map.containsKey().