Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
map
key
communitycreator

How to check if a map contains an entry for a key in Java

Programming Bytes

In Java, we can use the containsKey method to check if a map contains a mapping value for a key.

Syntax

Map.containsKey(Object key);

This method returns true if the mapping for the key is present and false otherwise.

Code

import java.util.HashMap;

class Main {
  public static void main(String[] args){

    // create a HashMap
    HashMap<Integer, String> numbers = new HashMap<>();

    // add mappings to the HashMap
    numbers.put(1, "One");
    numbers.put(2, "Two");
    numbers.put(3, "Three");
    System.out.println("The numbers map is =>" + numbers );

    System.out.println("\nChecking  if the key 1 is present in map =>" + numbers.containsKey(1));
    System.out.println("\nChecking  if the key 4 is present in map =>" + numbers.containsKey(4)); 
    
    System.out.println("\nAdding a mapping for key '4'");

    numbers.put(4, "four");
    System.out.println("\nChecking  if the key 4 is present in map =>" + numbers.containsKey(4)); 

  }
}

Explanation

In the code above, we have:

  • Created a Map with three values.

  • Checked if the mapping is presently using the containsKey method. For:

    • key 1 there is a mapping present, so the containsKey method will return true.
    • key 4 there is no mapping present, so the containsKey method will return false.
  • Added mapping for key-4 and checked if a mapping for key-4 is present. Since it is, the containsKey method will now return true.

RELATED TAGS

java
map
key
communitycreator
RELATED COURSES

View all Courses

Keep Exploring